实现代码
目录
写回调函数:
//获取到一个窗口就会调用一次
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
/*
* Remarks
The EnumWindows function does not enumerate child windows,
with the exception of a few top-level windows owned by the
system that have the WS_CHILD style.
*/
// EnumChildWindows(hwnd, EnumChildProc, lParam); 接着获取子窗口
wchar_t szClass[256];
// 滤掉不在任务栏显示的窗口
// 有些软件把显示窗口设为owned窗口,使用GW_OWNER检查不好
if(!GetWindow(hwnd,GW_OWNER)&&IsWindowVisible(hwnd))
{
GetClassName(hwnd,szClass,256);
//去掉桌面 progman 和任务栏本身
if(wcscmp(szClass,L"Progman")==0 || wcscmp(szClass,L"Progman") == 0 )
{
return false;
}
qInfo()<<hwnd;
wchar_t szTitle[256];
GetWindowTextW(hwnd,szTitle,256);
QString str = QString().fromStdWString(std::wstring(szTitle));
HICON hIcon = (HICON)SendMessage(hwnd, WM_GETICON, ICON_BIG, 0);
if(hIcon == 0)
{
#ifdef _WIN64
hIcon = (HICON)GetClassLongPtr(hwnd,GCLP_HICON);
#else
hIcon = (HICON)GetClassLongPtr(hwnd,GCL_HICON);
#endif
}
pThis->setPixIcon(hIcon,hwnd);
qInfo()<<str;
}
return true;
}
然后在主函数调用以下函数,每找到一个窗口都会调用一次EnumWindowsProc,然后选出所要的窗口句柄,获取图标
EnumWindows(EnumWindowsProc,0);
说明
参数:GW_OWNER
The retrieved handle identifies the specified window's owner window
参考 https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindow
获取图标的方法
//获取窗口图标, 窗口分配了特定图标
HICON icon = reinterpret_cast<HICON>(::SendMessageW(hwnd, WM_GETICON, ICON_SMALL, 0));
if (icon == 0) {
//替代方法。从窗口类获取
icon = reinterpret_cast<HICON>(::GetClassLongPtrW(hwnd, GCLP_HICONSM));
}
//替代方法:从主模块(进程的可执行映像)获取第一个图标,这个没有试,不太清楚
if (icon == 0) {
icon = ::LoadIcon(GetModuleHandleW(0), MAKEINTRESOURCE(0));
}
//替代方法。使用操作系统默认图标,没意义
if (icon == 0) {
icon = ::LoadIcon(0, IDI_APPLICATION);
}
Qt转换HICON为QPixmap
pro 加入 winextras
使用:
QPixmap pix = QtWin::fromHICON(hIcon);
Qt winextras模块:对windows api的一些封装
https://blog.csdn.net/cloud_castle/article/details/43672509
使用Qt5.6,QPixmap::fromWinHICON 已经没有了