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

时间:2010-01-08 17:43:54

标签: 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);

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);
    }
}

这只能获得Window标题和句柄ID。我想获得可执行文件名称(也许还有更多信息)。

我如何实现这一目标?

2 个答案:

答案 0 :(得分:7)

我认为你想要“GetWindowModuleFileName()”而不是GetWindowText 你传入了hwnd,所以你仍然需要调用GetForegroundWindow()

答案 1 :(得分:2)

快速谷歌搜索提供了一个例子,如C-Sharpcorner article