What is the correct way to create a single-instance WPF application?

前端 未结 30 3839
耶瑟儿~
耶瑟儿~ 2020-11-21 05:14

Using C# and WPF under .NET (rather than Windows Forms or console), what is the correct way to create an application that can only be run as a single instance?

I kno

30条回答
  •  孤城傲影
    2020-11-21 05:35

    Use mutex solution:

    using System;
    using System.Windows.Forms;
    using System.Threading;
    
    namespace OneAndOnlyOne
    {
    static class Program
    {
        static String _mutexID = " // generate guid"
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
    
            Boolean _isNotRunning;
            using (Mutex _mutex = new Mutex(true, _mutexID, out _isNotRunning))
            {
                if (_isNotRunning)
                {
                    Application.Run(new Form1());
                }
                else
                {
                    MessageBox.Show("An instance is already running.");
                    return;
                }
            }
        }
    }
    }
    

提交回复
热议问题