2014-03-05 26 views
4

我正在尝试获取活动窗口的名称,如任务管理器应用程序列表(使用c#)中所示。 我遇到了与here相同的问题。 我试图按照他们的描述做,但我有问题,而焦点的应用程序是图片库,我得到例外。 我也试过this,但没有给我我期望的结果。 现在我用:如何获取活动窗口应用程序名称,如任务管理器中所示

IntPtr handle = IntPtr.Zero; 
handle = GetForegroundWindow(); 

const int nChars = 256; 
StringBuilder Buff = new StringBuilder(nChars); 
if (GetWindowText(handle, Buff, nChars) > 0) 
{ 
    windowText = Buff.ToString(); 
} 

和删除基于我对最常用的应用程序创建的表什么是不相关的,但我不喜欢这样的解决方法。 有没有办法让应用程序的名称,因为它是在任务管理器中的所有正在运行的应用程序?

+0

究竟是什么你试图完成?获取活动窗口的窗口标题或正在运行的进程名称列表? –

+0

获取活动窗口的窗口标题,但不是全名,而是出现在任务管理器中的短名称。 – eskadi

回答

4

在阅读了很多内容之后,我将自己的代码分成了两种情况,分别是metro应用程序和所有其他应用程序。 我的解决方案处理我为地铁应用程序获得的异常以及我在平台上遇到的异常。 这是最终工作的代码:

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

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); 

[DllImport("user32.dll")] 
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); 

public string GetActiveWindowTitle() 
{ 
    var handle = GetForegroundWindow(); 
    string fileName = ""; 
    string name = ""; 
    uint pid = 0; 
    GetWindowThreadProcessId(handle, out pid); 

    Process p = Process.GetProcessById((int)pid); 
    var processname = p.ProcessName; 

    switch (processname) 
    { 
     case "explorer": //metro processes 
     case "WWAHost": 
      name = GetTitle(handle); 
      return name; 
     default: 
      break; 
    } 
    string wmiQuery = string.Format("SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId LIKE '{0}'", pid.ToString()); 
    var pro = new ManagementObjectSearcher(wmiQuery).Get().Cast<ManagementObject>().FirstOrDefault(); 
    fileName = (string)pro["ExecutablePath"]; 
    // Get the file version 
    FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(fileName); 
    // Get the file description 
    name = myFileVersionInfo.FileDescription; 
    if (name == "") 
     name = GetTitle(handle); 

return name; 
} 

public string GetTitle(IntPtr handle) 
{ 
string windowText = ""; 
    const int nChars = 256; 
    StringBuilder Buff = new StringBuilder(nChars); 
    if (GetWindowText(handle, Buff, nChars) > 0) 
    { 
     windowText = Buff.ToString(); 
    } 
    return windowText; 
} 
0

这听起来像你需要通过每个顶级窗口(直接桌面窗口的孩子,通过pinvoke http://msdn.microsoft.com/en-us/library/windows/desktop/ms633497(v=vs.85).aspx使用EnumWindows),然后调用GetWindowText pinvoke函数。

EnumWindows的将“通过手柄传递到每个窗口,反过来,到应用程序定义的回调函数枚举屏幕上的所有顶层窗口”。

+0

在您发送的链接中说:注意对于Windows 8和更高版本,EnumWindows仅列举桌面应用程序的顶级窗口。我在win8上工作,还需要metro应用程序名称。 – eskadi

+0

您可能可以使用GetWindow,但我没有使用Metro应用程序,所以无法确定。 –

相关问题