【问题标题】:How to set focus to another window?如何将焦点设置到另一个窗口?
【发布时间】:2012-06-05 13:49:30
【问题描述】:

我遇到了一个失去焦点的程序的问题。这不是我的程序。如何编写第二个程序以每 1-2 秒将焦点设置到该窗口?有可能吗?

【问题讨论】:

  • 您是说您希望焦点每秒钟在您的程序和其他第二个程序之间切换一次吗?或者在您的应用程序中希望每 2 秒将另一个程序带到前面(以防它再次回到后面)?
  • 是程序(不同的程序进程)还是你的子窗体?
  • 它的不同程序,我希望我的程序只关注它......

标签: c# winforms


【解决方案1】:

如果您想关注其他程序/进程,可以使用以下 Win32 API 调用。

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

private void BringToFront(Process pTemp)
{
    SetForegroundWindow(pTemp.MainWindowHandle);
}

【讨论】:

  • 在 Windows 上,你应该使用user32.dll,因为coredll.dll 是用于 Windows Mobile 的!
【解决方案2】:

使用 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.

【讨论】:

    猜你喜欢
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多