app
QSharedMemory shared("appID");
//attach成功表示已经存在该内存了,表示当前存在实例
if (shared.attach())//共享内存被占用则直接返回
return 0;
MainWindow w;
w.show();
qulonglong winID = (qulonglong)w.winId();
shared.create(32);
shared.lock();
memcpy(shared.data(), &winID, sizeof(qlonglong));
shared.unlock();
process
// 启动窗口
QProcess process;
process.start("app.exe");
process.waitForStarted();
QSharedMemory shareMem("appID");
if(!shareMem.isAttached())
shareMem.attach();
HWND winID;
shareMem.lock();
memcpy(&winID, shareMem.data(), sizeof (qulonglong));
shareMem.unlock();
shareMem.detach();
qDebug() << "id:" << winID <<"\n";
// 嵌入进程窗口显示
auto window = QWindow::fromWinId((WId)winID);
auto widget = QWidget::createWindowContainer(window, nullptr);
widget->show();
效果
注:调试崩溃会引起共享内存异常,需taskkill /f /im app.exe|process.exe