Click here to Skip to main content
15,847,653 members
Articles / Desktop Programming / Windows Forms
Alternative
Tip/Trick

Run Only One Copy Of Application

Rate me:
Please Sign up or sign in to vote.
4.92/5 (10 votes)
25 Mar 2011CPOL 11K   5   5
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:


C#
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;
            }
            ...
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
FDW
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
raj ch6-Jul-13 1:11
raj ch6-Jul-13 1:11 
GeneralReason for my vote of 5 The SetForgroundWindow is a nice fea... Pin
Roy from Detroit12-Dec-11 5:52
Roy from Detroit12-Dec-11 5:52 
Reason for my vote of 5
The SetForgroundWindow is a nice feature, it tries to help solve the original problem (that the user apparently lost the window), instead of simply stopping the user and increasing frustration.
GeneralHave not done a perf mon on both of the solutions, but findi... Pin
zenwalker198516-Oct-11 5:05
zenwalker198516-Oct-11 5:05 
GeneralReason for my vote of 5 nice alternative Pin
charles henington22-Apr-11 7:07
charles henington22-Apr-11 7:07 
GeneralReason for my vote of 5 Reason for my vote of 5 Nice way to... Pin
RK_DBA14-Apr-11 18:44
RK_DBA14-Apr-11 18:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.