阻止应用程序运行两次,而是显示第一个窗口

时间:2014-12-25 10:18:51

标签: c# wpf

我有一个wpf应用程序,我必须让应用程序只运行一次。一台机器上不应该有多个实例。

这是我在App.xaml.cs中的代码,在OnStartup()方法中:

var runningProcess = GetAnotherAppInstanceIfExists();

            if (runningProcess != null)
            {
                HandleMultipleInstances(runningProcess);
                Environment.Exit(0);
            }

public Process GetAnotherAppInstanceIfExists()
    {
        var currentProcess = Process.GetCurrentProcess();

        var appProcesses = new List<string> { "myApp", "myApp.vshost" };

        var allProcesses = Process.GetProcesses();

        var myAppProcess = (from process in allProcesses
            where process.Id != currentProcess.Id && appProcesses.Contains(process.ProcessName)
            select process).FirstOrDefault();

        if (myAppProcess != null)
        {
            return currentProcess;
        }

        return myAppProcess;
    }

public void HandleMultipleInstances(Process runningProcess)
    {
        SetForegroundWindow(runningProcess.MainWindowHandle);
        ShowWindow(runningProcess.MainWindowHandle, SW_RESTORE);
    }

因此,应用程序在第二次运行时,不会打开一个新实例,这很棒。但是,如果最小化,我需要找到第一个实例并再次显示窗口。这一行就是为了这个:

ShowWindow(runningProcess.MainWindowHandle, SW_RESTORE);

它不起作用。我究竟做错了什么?我在网上看了很多例子,我的代码和他们一样。

2 个答案:

答案 0 :(得分:0)

首先将App.xaml文件的构建操作更改为页面。然后,您可以在App.xaml.cs中使用此代码段:

private static readonly Mutex Mutex = new Mutex(true, "put your unique value here or GUID");
    private static MainWindow _mainWindow;       

    [STAThread]
    static void Main()
    {
        if (Mutex.WaitOne(TimeSpan.Zero, true))
        {
            var app = new App();
            _mainWindow = new MainWindow();
            app.Run(_mainWindow);
            Mutex.ReleaseMutex();
        }
        else
        {
            //MessageBox.Show("You can only run one instance!");
            _mainWindow.WindowState = WindowState.Maximized;
        }
    }

答案 1 :(得分:0)

对我来说,解决方案是这样做:

将您的App.xaml文件的生成操作更改为Page。 (右键单击文件,然后properties => Build Action =>下拉至page

在App.xaml.cs中:

    private static readonly Mutex Mutex = new Mutex(true, "42ae83c2-03a0-472e-a2ea-41d69524a85b"); // GUI can be what you want !
    private static App _app;

    [STAThread]
    static void Main()
    {
        if (Mutex.WaitOne(TimeSpan.Zero, true))
        {
            _app = new App();
            _app.InitializeComponent();
            _app.Run();
            Mutex.ReleaseMutex();
        }
        else
        {
            //MessageBox.Show("You can only run one instance!");
            _app.MainWindow.WindowState = WindowState.Maximized;
        }
    }