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
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With