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

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

    I can't find a short solution here so I hope someone will like this:

    UPDATED 2018-09-20

    Put this code in your Program.cs:

    using System.Diagnostics;
    
    static void Main()
    {
        Process thisProcess = Process.GetCurrentProcess();
        Process[] allProcesses = Process.GetProcessesByName(thisProcess.ProcessName);
        if (allProcesses.Length > 1)
        {
            // Don't put a MessageBox in here because the user could spam this MessageBox.
            return;
        }
    
        // Optional code. If you don't want that someone runs your ".exe" with a different name:
    
        string exeName = AppDomain.CurrentDomain.FriendlyName;
        // in debug mode, don't forget that you don't use your normal .exe name.
        // Debug uses the .vshost.exe.
        if (exeName != "the name of your executable.exe") 
        {
            // You can add a MessageBox here if you want.
            // To point out to users that the name got changed and maybe what the name should be or something like that^^ 
            MessageBox.Show("The executable name should be \"the name of your executable.exe\"", 
                "Wrong executable name", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
    
        // Following code is default code:
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
    

提交回复
热议问题