使用 EnumWindows 找到知足你要求的窗口
2019-04-30 13:11 html
在 Windows 应用开发中,若是须要操做其余的窗口,那么可使用 EnumWindows
这个 API 来枚举这些窗口。windows
本文介绍使用 EnumWindows
来枚举并找到本身关心的窗口(如 QQ/TIM 窗口)。api
EnumWindows
你能够在微软官网了解到 EnumWindows
。app
要在 C# 代码中使用 EnumWindows
,你须要编写平台调用 P/Invoke 代码。使用我在另外一篇博客中的方法能够自动生成这样的平台调用代码:函数
我这里直接贴出来:post
[DllImport("user32.dll")]
public static extern int EnumWindows(WndEnumProc lpEnumFunc, int lParam);
遍历全部的顶层窗口
官方文档对此 API 的描述是:ui
Enumerates all top-level windows on the screen by passing the handle to each window, in turn, to an application-defined callback function.url
遍历屏幕上全部的顶层窗口,而后给回调函数传入每一个遍历窗口的句柄。spa
不过,并非全部遍历的窗口都是顶层窗口,有一些非顶级系统窗口也会遍历到,详见:EnumWindows 中的备注节。.net
因此,若是须要遍历获得全部窗口的集合,那么可使用以下代码:
public static IReadOnlyList<int> EnumWindows()
{
var windowList = new List<int>();
EnumWindows(OnWindowEnum, 0);
return windowList;
bool OnWindowEnum(int hwnd, int lparam)
{
// 可自行加入一些过滤条件。
windowList.Add(hwnd);
return true;
}
}
遍历具备指定类名或者标题的窗口
咱们须要添加一些能够用于过滤窗口的 Win32 API。如下是咱们即将用到的两个:
// 获取窗口的类名。
[DllImport("user32.dll")]
private static extern int GetClassName(int hWnd, StringBuilder lpString, int nMaxCount);
// 获取窗口的标题。
[DllImport("user32")]
public static extern int GetWindowText(int hwnd, StringBuilder lptrString, int nMaxCount);
因而根据类名找到窗口的方法:
public static IReadOnlyList<int> FindWindowByClassName(string className)
{
var windowList = new List<int>();
EnumWindows(OnWindowEnum, 0);
return windowList;
bool OnWindowEnum(int hwnd, int lparam)
{
var lpString = new StringBuilder(512);
GetClassName(hwnd, lpString, lpString.Capacity);
if (lpString.ToString().Equals(className, StringComparison.InvariantCultureIgnoreCase))
{
windowList.Add(hwnd);
}
return true;
}
}
使用此方法,咱们能够传入 "txguifoundation"
找到 QQ/TIM 的窗口:
var qqHwnd = FindWindowByClassName("txguifoundation");
要获取窗口的标题,或者把标题做为过滤条件,则使用 GetWindowText
。
在 QQ/TIM 中,窗口的标题是聊天对方的名字或者群聊名称。
var lptrString = new StringBuilder(512);
GetWindowText(hwnd, lptrString, lptrString.Capacity);
参考资料
- EnumWindows function (winuser.h) - Microsoft Docs
- GetClassName function (winuser.h) - Microsoft Docs
本文会常常更新,请阅读原文: https://blog.walterlv.com/post/find-specific-window-by-enum-windows.html ,以免陈旧错误知识的误导,同时有更好的阅读体验。
若是你想持续阅读个人最新博客,请点击 RSS 订阅,或者前往 CSDN 关注个人主页。
本做品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、从新发布,但务必保留文章署名 吕毅 (包含连接: https://blog.walterlv.com ),不得用于商业目的,基于本文修改后的做品务必以相同的许可发布。若有任何疑问,请 与我联系 (walter.lv@qq.com) 。