c++ 在顶层窗口里搜索名称包含某个字符串的窗口,获取其窗口句柄 的代码
时间: 2023-12-06 17:45:42 浏览: 169
以下是使用 C++ 在顶层窗口中搜索名称包含某个字符串的窗口,获取其窗口句柄的代码:
```cpp
#include <Windows.h>
#include <string>
// 搜索窗口名称包含指定字符串的窗口
HWND FindWindowByTitleSubstring(const std::wstring& substring)
{
HWND hwnd = NULL;
while ((hwnd = FindWindowEx(NULL, hwnd, NULL, NULL)) != NULL)
{
TCHAR title[1024];
GetWindowText(hwnd, title, sizeof(title));
if (_tcsstr(title, substring.c_str()) != NULL)
{
return hwnd;
}
}
return NULL;
}
int main()
{
// 搜索窗口名中包含 "Notepad" 的窗口
HWND hwnd = FindWindowByTitleSubstring(L"Notepad");
if (hwnd != NULL)
{
// 找到了窗口,可以对其进行操作
// 例如:发送一条消息给窗口
SendMessage(hwnd, WM_CLOSE, 0, 0);
}
return 0;
}
```
该代码使用了 Win32 API 中的 `FindWindowEx` 函数来在顶层窗口中搜索窗口。通过遍历每个窗口并使用 `GetWindowText` 函数获取窗口名称,再使用 `_tcsstr` 函数判断名称是否包含指定的字符串。如果找到了匹配的窗口,就返回其句柄。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)