2010-01-08 133 views
5

我有一个应用程序,我想在后台运行。我想获取可执行文件的名称,例如IExplorer.exe。我玩过以下代码:C#获取有关当前活动窗口的信息

[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。我想获得可执行文件的名称(也许更多的信息)。

我该如何做到这一点?

+0

看这个问题的计算器上的最后一个答案: http://stackoverflow.com/questions/7268302/get-the-titles-of-all-open-windows/31517889#31517889 – Godvicien 2015-07-20 13:44:30

回答

7

我想你想“GetWindowModuleFileName()”,而不是GetWindowText时 您通过在HWND,所以你仍然需要调用GetForegroundWindow()

+0

钙我使用事件来获得屏幕标题,即当用户改变屏幕焦点时,它应该触发@ – CodeIt 2016-05-23 21:55:56

2

快速谷歌搜索带来了这样一个例子C-Sharpcorner article

+2

虽然此链接可能回答这个问题,最好在这里包含答案的基本部分,并提供参考链接。如果链接页面更改,则仅链接答案可能会失效。 – Joel 2014-02-19 12:25:35

相关问题