查找并激活应用程序窗口

Leo*_* Vo 17 .net c#

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

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

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

Han*_*ant 26

你需要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);
}
Run Code Online (Sandbox Code Playgroud)

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