Search code examples
c#.netwpfsingle-instance

How to check if a WPF application is already running?


Possible Duplicate:
What is the correct way to create a single instance application?

How can I check if my application is already open? If my application is already running, I want to show it instead of opening a new instance.


Solution

  • [DllImport("user32.dll")]
    private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);
    
    static void Main() 
    {
        Process currentProcess = Process.GetCurrentProcess();
        var runningProcess = (from process in Process.GetProcesses()
                              where
                                process.Id != currentProcess.Id &&
                                process.ProcessName.Equals(
                                  currentProcess.ProcessName,
                                  StringComparison.Ordinal)
                              select process).FirstOrDefault();
        if (runningProcess != null)
        {
            ShowWindow(runningProcess.MainWindowHandle, SW_SHOWMAXIMIZED);
           return; 
        }
    }
    

    Method 2

    static void Main()
    {
        string procName = Process.GetCurrentProcess().ProcessName;
    
        // get the list of all processes by the "procName"       
        Process[] processes=Process.GetProcessesByName(procName);
    
        if (processes.Length > 1)
        {
            MessageBox.Show(procName + " already running");  
            return;
        } 
        else
        {
            // Application.Run(...);
        }
    }