1) Import the following DLLS:
[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr WindowHandle);
public const int SW_RESTORE = 9;
* Don't forget to add the using statement:
using System.Runtime.InteropServices;
2) Identify the process you want to bring to the front and set the focus on it's window handle:
private void FocusProcess(string procName)
{
Process[] objProcesses = System.Diagnostics.Process.GetProcessesByName(procName); if (objProcesses.Length > 0)
{
IntPtr hWnd = IntPtr.Zero;
hWnd = objProcesses[0].MainWindowHandle;
ShowWindowAsync(new HandleRef(null,hWnd), SW_RESTORE);
SetForegroundWindow(objProcesses[0].MainWindowHandle);
}
}
Thank you, I have used this method with success.
ReplyDeleteThank you, it works great !!!
ReplyDeleteKochav
Love you buddy. The only code which works like a charm.
ReplyDeleteI want to give the focus to the last active (focused) application (whichever it is, for example Notepad, Chrome).. How can I do that?
ReplyDeleteThanks. Very Helpful.
ReplyDeletethanks so much.
ReplyDeleteNot working for me. How to Identify the process I want?
ReplyDeleteOh. Now It's working. I was puting the process name with the .exe
DeleteThank Buddy...
6 years later, and this is still a great help. Thanks
ReplyDeleteThanks. This saved me.
ReplyDeleteThankyou. I adapted to use GetProcessById and it works wonderfully.
ReplyDeleteit is a code
ReplyDeletethank you it's work with notepad , but I tried to focus chrome not working.
ReplyDelete