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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2029495/
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-06 22:49:56  来源:igfitidea点击:

C# get information about current active window

c#processwindow

提问by KasperJohansen

I have an application which i want to run in the background. I want to get the executable name, for an example IExplorer.exe. I have played around with the following code:

我有一个要在后台运行的应用程序。我想获取可执行文件名称,例如 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);
    }
}

That only gets me the Window title, and the handle ID. I want to get the executable name (and maybe more information).

那只会让我得到窗口标题和句柄 ID。我想获取可执行文件名称(也许还有更多信息)。

How do i achieve that?

我如何做到这一点?

采纳答案by taylonr

I think you want "GetWindowModuleFileName()" instead of GetWindowText You pass in the hwnd, so you'll still need the call to GetForegroundWindow()

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

回答by Jamie Altizer

A quick google search brings up an example such as C-Sharpcorner article

一个快速的谷歌搜索带来了一个例子,比如C-Sharpcorner 文章