C# 如何将焦点设置到另一个窗口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10898560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:42:08  来源:igfitidea点击:

How to set focus to another window?

c#winforms

提问by Endiss

I have a problem with a program that loses focus. It's not my program. How can I write a second program to set focus to that window every 1-2 seconds? Is is possible to do that?

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

采纳答案by Rajesh Subramanian

You can use following Win32 API if you want to bring some other program/process

如果你想带一些其他的程序/进程,你可以使用以下 Win32 API

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

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

回答by Pradeep Bogati

use spy++ or other ui tools to find the class name of the window you want to focus, say its: focusWindowClassName. Then add the below functions:

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