C#获取有关当前活动窗口的信息

C#获取有关当前活动窗口的信息,c#,process,window,C#,Process,Window,我有一个应用程序,我想在后台运行。我想获取可执行文件名,例如IExplorer.exe。我使用了以下代码: [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count); publi

我有一个应用程序,我想在后台运行。我想获取可执行文件名,例如IExplorer.exe。我使用了以下代码:

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

public static void Main()
{
    int chars = 256;
    StringBuilder buff = new StringBuilder(chars);
    while (true)
    {
        // Obtain the handle of the active window.
        IntPtr handle = GetForegroundWindow();

        // Update the controls.
        if (GetWindowText(handle, buff, chars) > 0)
        {
            Console.WriteLine(buff.ToString());
            Console.WriteLine(handle.ToString());
        }
        Thread.Sleep(1000);
    }
}
这只会获取窗口标题和句柄ID。我想获取可执行文件名(可能还有更多信息)

如何实现这一点?

我认为您需要“()”而不是GetWindowText
您传入了hwnd,因此您仍然需要调用GetForeGroundIndow()

一个快速的google搜索会出现一个例子,例如

,虽然此链接可能会回答问题,但最好在此处包含答案的基本部分,并提供链接供参考。如果链接页面更改,仅链接的答案可能会无效。请查看stackoverflow上此问题的最后一个答案:我是否可以使用事件获取屏幕标题,即当用户更改屏幕焦点时,它应该触发@