#include "mainwindow.h"
#include <QApplication>
#include <QGridLayout>
#include <QThread>
#include <Windows.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
// 查找Chrome主窗口(根据实际情况调整类名)
HWND hwndChrome = FindWindowW(L"SPChrome_FrameWin_1", nullptr);
if (!hwndChrome) {
qDebug() << "未找到Chrome窗口";
return -1;
}
// 创建Qt子窗口
QWidget *childWidget = new QWidget();
childWidget->setWindowTitle("Qt子窗口");
// 获取Qt窗口句柄
HWND hwndQt = reinterpret_cast<HWND>(childWidget->winId());
// 设置父子关系
if (!SetParent(hwndQt, hwndChrome)) {
qDebug() << "设置父窗口失败:" << GetLastError();
return -1;
}
//将D3D窗口添加上WS_CLIPSIBLINGS样式,让其不影响Qt窗口限时 这一步很重要
HWND intermediateWnd = FindWindowEx(hwndChrome, NULL, L"Chrome_RenderWidgetHostHWND", NULL);
if (intermediateWnd) {
LONG_PTR style = GetWindowLongPtr(intermediateWnd, GWL_STYLE);
SetWindowLongPtr(intermediateWnd, GWL_STYLE, style | WS_CLIPSIBLINGS);
SetWindowPos(intermediateWnd, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
}
//这是判断Qt窗口是否是最顶层,如果不是则将Qt窗口设置在最顶层
HWND hwnd = (HWND)childWidget->winId();
HWND parentHwnd = GetParent(hwnd);
HWND topHwnd = GetTopWindow(parentHwnd);
if(hwnd != topHwnd)
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
//通过这个接口来设置Qt窗口的位置大小
childWidget->setGeometry(100, 100, 500, 500);
childWidget->show();
char buffer[50];
char parent[50];
char child[50];
sprintf_s(buffer, "%p", w.winId());
sprintf_s(parent, "%p", hwndChrome);
sprintf_s(child, "%p", intermediateWnd);
qDebug() << "HWND value: "<<buffer;
qDebug() << "parent HWND value: "<<parent;
qDebug() << "child HWND value: "<<child;
return a.exec();
}
运行实现效果如下:
通过命令打开SPY++工具
通过SPY++工具查看层级效果如下
所以在通过函数 FindWindowW 查询google的主窗口的类别为SPChrome_FrameWin_1。