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

前端 未结 30 3253
耶瑟儿~
耶瑟儿~ 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条回答
  •  猫巷女王i
    2020-11-21 05:42

    Here is what I use. It combined process enumeration to perform switching and mutex to safeguard from "active clickers":

    public partial class App
    {
        [DllImport("user32")]
        private static extern int OpenIcon(IntPtr hWnd);
    
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
    
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var p = Process
               .GetProcessesByName(Process.GetCurrentProcess().ProcessName);
                foreach (var t in p.Where(t => t.MainWindowHandle != IntPtr.Zero))
                {
                    OpenIcon(t.MainWindowHandle);
                    SetForegroundWindow(t.MainWindowHandle);
                    Current.Shutdown();
                    return;
                }
    
                // there is a chance the user tries to click on the icon repeatedly
                // and the process cannot be discovered yet
                bool createdNew;
                var mutex = new Mutex(true, "MyAwesomeApp", 
                   out createdNew);  // must be a variable, though it is unused - 
                // we just need a bit of time until the process shows up
                if (!createdNew)
                {
                    Current.Shutdown();
                    return;
                }
    
                new Bootstrapper().Run();
            }
        }
    

提交回复
热议问题