我对一个失去焦点的程序有疑问。这不是我的计划。如何编写第二个程序,每隔1-2秒将焦点设置到该窗口?有可能这样做吗?
答案 0 :(得分:15)
如果您想带一些其他程序/进程
,可以使用以下Win32 API [DllImport("user32.dll")]
static extern bool SetForegroundWindow (IntPtr hWnd);
private void BringToFront(Process pTemp)
{
SetForegroundWindow(pTemp.MainWindowHandle);
}
答案 1 :(得分:4)
使用spy ++或其他ui工具查找要关注的窗口的类名称,例如:focusWindowClassName。然后添加以下功能:
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[System.Runtime.InteropServices.DllImport("User32.dll")]
public static extern bool ShowWindow(IntPtr handle, int nCmdShow);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
//Then:
// [Edit] Changed IntPrt to IntPtr
IntPtr hWnd = FindWindow("focusWindowClassName", null); // this gives you the handle of the window you need.
// then use this handle to bring the window to focus or forground(I guessed you wanted this).
// sometimes the window may be minimized and the setforground function cannot bring it to focus so:
/*use this ShowWindow(IntPtr handle, int nCmdShow);
*there are various values of nCmdShow 3, 5 ,9. What 9 does is:
*Activates and displays the window. If the window is minimized or maximized, *the system restores it to its original size and position. An application *should specify this flag when restoring a minimized window */
ShowWindow(hWnd, 9);
//The bring the application to focus
SetForegroundWindow(hWnd);
// you wanted to bring the application to focus every 2 or few second
// call other window as done above and recall this window again.