[英]How do I get the classname of the active window?
By using this code I can get the title of the active window..通过使用此代码,我可以获得活动的标题 window..
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private string GetActiveWindowTitle()
{
const int nChars = 256;
IntPtr handle = IntPtr.Zero;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
But how should I do to get the classname of the active window?但是我应该如何获取活动的 window 的类名呢?
Simply pinvoke GetClassName(). 只需要调用GetClassName()即可。 This returns the Windows class name for a window, it doesn't have anything to do with a C# class. 这将返回窗口的Windows类名,它与C#类没有任何关系。 Getting the C# class name for a window in another process is not possible. 无法在另一个进程中获取窗口的C#类名。 Take a look at the Managed Spy++ tool for possible hacks if this is a Winforms app. 如果这是一个Winforms应用程序,请查看Managed Spy ++工具以获取可能的黑客攻击。
I expanded Hans Passant's answer into working code:我将 Hans Passant 的答案扩展为工作代码:
Usage:用法:
string className = Spy.GetForegroundWindowClassName();
Class: Class:
using System.Runtime.InteropServices;
using System.Text;
public static class Spy
{
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
public static string GetForegroundWindowClassName()
{
IntPtr hWnd = GetForegroundWindow();
var className = new StringBuilder(256);
GetClassName(hWnd, className, className.Capacity);
return className.ToString();
}
}
Side Note: in my case, I just needed a basic utility to tell me the class name of a window so I could reference that in my C# code.旁注:在我的例子中,我只需要一个基本实用程序来告诉我 window 的 class 名称,这样我就可以在我的 C# 代码中引用它。 After writing the code above, I realized I could achieve the same thing using pre-existing utilities.写完上面的代码后,我意识到我可以使用预先存在的实用程序来实现同样的事情。 One such utility I see mentioned often in the C# community is Visual Studio's Spy++ tool.我在 C# 社区中看到经常提到的此类实用程序之一是 Visual Studio 的 Spy++ 工具。 I didn't bother trying that since it requires downloading 2.5 GB of C++ components.我没有尝试这样做,因为它需要下载 2.5 GB 的 C++ 组件。 Instead, I used the "Window Spy" tool that comes with Autohotkey.相反,我使用了 Autohotkey 附带的“Window Spy”工具。 Autohotkey is a tiny download compared to what's needed for Spy++, so I think it's a good option if it suits your needs.与 Spy++ 所需的下载相比, Autohotkey的下载量很小,所以我认为如果它适合您的需要,它是一个不错的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.