WPF Single Instance Best Practices

前端 未结 11 1531
名媛妹妹
名媛妹妹 2020-12-07 08:19

This is the code I implemented so far to create a single instance WPF application:

#region Using Directives
using System;
using System.Globalization;
using S         


        
11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 09:20

    There are Several choices,

    • Mutex
    • Process manager
    • Named Semaphore
    • Use a listener socket

    Mutex

    Mutex myMutex ;
    
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        bool aIsNewInstance = false;
        myMutex = new Mutex(true, "MyWPFApplication", out aIsNewInstance);  
        if (!aIsNewInstance)
        {
            MessageBox.Show("Already an instance is running...");
            App.Current.Shutdown();  
        }
    }
    

    Process manager

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        Process proc = Process.GetCurrentProcess();
        int count = Process.GetProcesses().Where(p=> 
            p.ProcessName == proc.ProcessName).Count();
    
        if (count > 1)
        {
            MessageBox.Show("Already an instance is running...");
            App.Current.Shutdown(); 
        }
    }
    

    Use a listener socket

    One way to signal another application is to open a Tcp connection to it. Create a socket, bind to a port, and listen on a background thread for connections. If this succeeds, run normally. If not, make a connection to that port, which signals the other instance that a second application launch attempt has been made. The original instance can then bring its main window to the front, if appropriate.

    “Security” software / firewalls might be an issue.

    Single Instance Application C#.Net along with Win32

提交回复
热议问题