Check if other instances of a WPF application are/aren't running

This question already has an answer here:

  • What is the correct way to create a single-instance application? 35 answers

  • The get processes by name strategy can fail if the exe has been copied and renamed. Debugging can also be problematic because .vshost is appended to the process name.

    To create a single instance application in WPF, you can start by removing the StartupUri attribute from the App.Xaml file so that it looks like this...

    <Application x:Class="SingleInstance.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    </Application>
    

    After that, you can go to the App.xaml.cs file and change it so it looks like this...

    public partial class App 
    {
        // give the mutex a  unique name
        private const string MutexName = "##||ThisApp||##";
        // declare the mutex
        private readonly Mutex _mutex;
        // overload the constructor
        bool createdNew;
        public App() 
        {
            // overloaded mutex constructor which outs a boolean
            // telling if the mutex is new or not.
            // see http://msdn.microsoft.com/en-us/library/System.Threading.Mutex.aspx
            _mutex = new Mutex(true, MutexName, out createdNew);
            if (!createdNew)
            {
                // if the mutex already exists, notify and quit
                MessageBox.Show("This program is already running");
                Application.Current.Shutdown(0);
            }
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            if (!createdNew) return;
            // overload the OnStartup so that the main window 
            // is constructed and visible
            MainWindow mw = new MainWindow();
            mw.Show();
        }
    }
    

    This will test if the mutex exists and if it does exist, the app will display a message and quit. Otherwise the application will be constructed and the OnStartup override will be called.

    Depending upon your version of Windows, raising the message box will also push the existing instance to the top of the Z order. If not you can ask another question about bringing a window to the top.

    There are additional features in the Win32Api that will help further customize the behaviour.

    This approach gives you the message notification you were after and assures that only one instance of the main window is ever created.

    链接地址: http://www.djcxy.com/p/51142.html

    上一篇: 只启动一次应用程序C#

    下一篇: 检查WPF应用程序的其他实例是否正在运行