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

前端 未结 30 3177
耶瑟儿~
耶瑟儿~ 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:30

    Not using Mutex though, simple answer:

    System.Diagnostics;    
    ...
    string thisprocessname = Process.GetCurrentProcess().ProcessName;
    
    if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
                    return;
    

    Put it inside the Program.Main().
    Example:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Diagnostics;
    
    namespace Sample
    {
        static class Program
        {
            /// 
            /// The main entry point for the application.
            /// 
            [STAThread]
            static void Main()
            {
                //simple add Diagnostics namespace, and these 3 lines below 
                string thisprocessname = Process.GetCurrentProcess().ProcessName;
                if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
                    return;
    
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Sample());
            }
        }
    }
    

    You can add MessageBox.Show to the if-statement and put "Application already running".
    This might be helpful to someone.

提交回复
热议问题