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

我有一个应用程序,我想在后台运行。 我想获取可执行文件名,例如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。 我想获得可执行文件名称(也许还有更多信息)。

我如何实现这一目标?

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

快速谷歌搜索提出了一个例子,如C-Sharpcorner文章