查找并激活应用程序窗口

假设notepad.exe正在打开,并且它的窗口处于非活动状态。 我将编写一个应用程序来激活它。 怎么做?

更新:窗口标题未定义。 所以,我不喜欢使用基于窗口标题的FindWindow。

我的应用程序是Winform C#2.0。 谢谢。

你需要P / invoke SetForegroundWindow()。 Process.MainWindowHandle可以为您提供所需的句柄。 例如:

using System; using System.Diagnostics; using System.Runtime.InteropServices; class Program { static void Main(string[] args) { var prc = Process.GetProcessesByName("notepad"); if (prc.Length > 0) { SetForegroundWindow(prc[0].MainWindowHandle); } } [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); } 

如果您有多个记事本副本正在运行,请注意歧义。

您需要PInvoke Windows API调用,如FindWindow和/或EnumWindows和GetWindowText(用于标题)。 理想情况下,您可能还希望使用GeWindowThreadProcessId,以便将其与实际过程联系起来。

你必须使用这些的组合 –

在运行时切换Process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

当ShowInTaskbar = false时,将另一个进程窗口置于前台

您需要找到窗口的类并对其进行搜索。 在这里阅读更多相关信息 。

仅供参考,Notepad的类名是“Notepad”(不带引号)。 您可以使用Spy ++进行validation。

注意:如果应用程序的窗口没有窗口运行,则无法激活该窗口 。 在这里阅读API中的更多选项。