Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i set the focus to application which is already in running state?

Tags:

c#

I have developed a C# Windows application & created a exe of it.

What I want is that when ever I try to run the application, if it is already in running state, then activate that application instance, else start new application.

That means I don't want to open same application more than one time

like image 929
Ayush Avatar asked Sep 09 '11 05:09

Ayush


2 Answers

Use the following code to set focus to the current application:

        [DllImport("user32.dll")]
        internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        ... 
        Process currentProcess = Process.GetCurrentProcess();
        IntPtr hWnd = currentProcess.MainWindowHandle;
        if (hWnd != IntPtr.Zero)
        {
            SetForegroundWindow(hWnd);
            ShowWindow(hWnd, User32.SW_MAXIMIZE);
        }
like image 143
Jacob Seleznev Avatar answered Nov 02 '22 03:11

Jacob Seleznev


You can PInvoke SetForegroundWindow() and SetFocus() from user32.dll to do this.

[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);

// SetFocus will just focus the keyboard on your application, but not bring your process to front.
// You don't need it here, SetForegroundWindow does the same.
// Just for documentation.
[DllImport("user32.dll")]
static extern IntPtr SetFocus(HandleRef hWnd);

As argument you pass the window handle of the process you want to bring in the front and focus.

SetForegroundWindow(myProcess.MainWindowHandle);

SetFocus(new HandleRef(null, myProcess.Handle)); // not needed

Also see the restrictions of the SetForegroundWindow Methode on msdna.

like image 36
Felix C Avatar answered Nov 02 '22 03:11

Felix C