One App Running at a time

cholden
cholden used Ask the Experts™
on
I have a C# app that should not have multiple instances running.

And if there is another instance running then kill the old process and run the one user is currently opening.

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Maybe the simplest way:
using System.Diagnostics;
Process[] processes = Process.GetProcessesByName("myapp");
foreach (Process p in processes)
{
    IntPtr pFoundWindow = p.MainWindowHandle;
    // Do something with the handle...
    p.CloseMainWindow();
}
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx
I used this in an app I did.  It doesn't kill the first process, it restores it.

   
static class Program
    {
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);
 
        [DllImport("user32.dll")]
        static extern bool IsIconic(IntPtr hWnd);
 
        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        
        const int SW_RESTORE = 9;
        
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //Only run 1 instance of this application.
            IntPtr hWnd = FindWindow(null, "Your Application");//title bar text of the window you are looking for.
 
            if (hWnd == IntPtr.Zero)//then this is the first instance.
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);                
                Application.Run(new Form1());
            }
            else//show the first instance.
            {
                SetForegroundWindow(hWnd);
 
                // If program is minimized, restore it.
                if (IsIconic(hWnd))
                {
                    ShowWindow(hWnd, SW_RESTORE);
                }
            }                           
        }
    }

Open in new window

Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Ooops... forgot to say, put that code into Program.cs.

Author

Commented:
Axshun I used your code and it seems to work except for my Form1 is hiden and when I run the code it becomes visible.

How can I solve this?

Thanks

Author

Commented:
Got it thanks Axshun.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial