65.9K
CodeProject is changing. Read more.
Home

Run Only One Copy Of Application

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.92/5 (10 votes)

Mar 25, 2011

CPOL
viewsIcon

12730

Maybe this is helpful, it tries to switch to the first running instance:namespace UltraSimple.Win{ static class Program { [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); [STAThread] ...

Maybe this is helpful, it tries to switch to the first running instance:

namespace UltraSimple.Win
{
    static class Program
    {
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        [STAThread]
        static void Main()
        {
            Process oProcess = Process.GetCurrentProcess();
            Process[] aoProcesses = Process.GetProcessesByName(oProcess.ProcessName);
            if (aoProcesses.Length > 1)
            {
                MessageBox.Show(
                      "The application \""
                    + oProcess.ProcessName
                    + "\" is already running.", "Ultrasimple");
                Program.SetForegroundWindow(aoProcesses[aoProcesses[0].Id == 
                        oProcess.Id ? 1 : 0].MainWindowHandle);
                return;
            }
            ...
        }
    }
}