wpf程序,只允许运行一个程序实例问题、

时间:2021-01-26 19:44:37

public partial class App : Application
{
    [DllImport("User32.dll")]
    private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

    [DllImport("User32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

    protected override void OnStartup(StartupEventArgs e)
    {
        if (!是否已运行)
        {
            //自动主程序
        }
        else
        {
            Application.Current.Shutdown();
            ShowWindowAsync(process.mainWindowHandle, 9);
            SetForegroundWindow(process.mainWindowHandle);
            //实现效果为,当程序已经启动了,再次启动时,将之前已启动的主程序显示出来。
            //当主程序是 Visibility = Visibility.Visible; 的时候可以达到效果,
              //但是当主程序是 Visibility = Visibility.Hidden 的时候,用上面的方式显示不出来,请问要怎么样才能显示出来呢。
        }
    }
}

5 个解决方案

#1


外行了,看不懂

#2



Visibility = Visibility.Hidden 
//是为了实现托盘,

#3


进程同步请使用System.Threading.Mutex

#4


引用 3 楼 wddw1986 的回复:
进程同步请使用System.Threading.Mutex



static System.Threading.Mutex mutex;

protected override void OnStartup(StartupEventArgs e)
{
    mutex = new System.Threading.Mutex(true, "Main");
    if (!mutex.WaitOne(0, false))
    {
        Application.Current.Shutdown();
        //这里用什么方式 显示主窗体呢,
    }
    else
    {
        mutex.ReleaseMutex();
        //启动主程序
    }
}

#5


引用 3 楼 wddw1986 的回复:
进程同步请使用System.Threading.Mutex


http://codereview.stackexchange.com/questions/20871/wpf-single-instance-best-practices

ok. 已参照这里 解决了 

#1


外行了,看不懂

#2



Visibility = Visibility.Hidden 
//是为了实现托盘,

#3


进程同步请使用System.Threading.Mutex

#4


引用 3 楼 wddw1986 的回复:
进程同步请使用System.Threading.Mutex



static System.Threading.Mutex mutex;

protected override void OnStartup(StartupEventArgs e)
{
    mutex = new System.Threading.Mutex(true, "Main");
    if (!mutex.WaitOne(0, false))
    {
        Application.Current.Shutdown();
        //这里用什么方式 显示主窗体呢,
    }
    else
    {
        mutex.ReleaseMutex();
        //启动主程序
    }
}

#5


引用 3 楼 wddw1986 的回复:
进程同步请使用System.Threading.Mutex


http://codereview.stackexchange.com/questions/20871/wpf-single-instance-best-practices

ok. 已参照这里 解决了