esk*_*adi 6 c# winapi hwnd active-window
我正在尝试获取活动窗口的名称,如任务管理器应用程序列表中所示(使用 c#)。我遇到了与此处所述相同的问题。我试图按照他们的描述去做,但是我遇到了问题,而重点应用程序是我得到异常的图片库。我也试过这个,但没有给我预期的结果。现在我使用:
IntPtr handle = IntPtr.Zero;
handle = GetForegroundWindow();
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
if (GetWindowText(handle, Buff, nChars) > 0)
{
windowText = Buff.ToString();
}
Run Code Online (Sandbox Code Playgroud)
并根据我为大多数常见应用程序创建的表删除不相关的内容,但我不喜欢这种解决方法。有没有办法获取所有正在运行的应用程序的任务管理器中的应用程序名称?
经过大量阅读后,我将代码分为两种情况,用于地铁应用程序和所有其他应用程序。我的解决方案处理地铁应用程序的异常以及有关平台的异常。这是最终起作用的代码:
[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;
}
Run Code Online (Sandbox Code Playgroud)