我在 Visual Studio 中制作了运行 Qt 应用程序(Qt 版本 5.11.1)的单个实例。一旦它第一次执行,我的主窗口就会打开,我正在关闭它。它一直在后台运行。
当我第二次运行.exe时,我想打开我第一次打开的前一个主窗口。
我正在枚举可用的窗口标题,并且我得到了"Test Window" 标题。但是使用此 HWND 我试图使用 SetForegroundWindow(hwnd);
在每个其他窗口的顶部设置前景。
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
if (IsWindowVisible(hwnd)) // check whether window is visible
{
char wnd_title[256];
GetWindowText(hwnd, wnd_title, sizeof(wnd_title));
MessageBox(0, wnd_title, "Installation Error", MB_OK | MB_ICONEXCLAMATION);
if (strcmp(wnd_title, "Test Window") == 0)
{
SetForegroundWindow(hwnd);
int err = GetLastError();
string msg = "error code " + std::to_string(err);
MessageBox(0, msg.c_str(),"Installation Error ", MB_OK | MB_ICONEXCLAMATION);
return false;
}
}
return true; // function must return true if you want to continue enumeration
}
当我第二次运行时,如何在所有其他窗口之上打开 Qt MainWindow。
最佳答案
检查在 https://github.com/qtproject/qt-solutions 中找到的项目 QtSingleApplication .
在QtSingleApplication 类中有一个名为activateWindow 的方法。在 Loader 示例中,只要运行程序的第二个实例,就会调用此方法。
要在您尝试打开第二个实例时使主窗口位于顶部,您必须像这样修改此方法。
void QtSingleApplication::activateWindow()
{
if (actWin) {
actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized);
actWin->activateWindow();
actWin->raise();
//winapi call
SetWindowPos((HWND)actWin->winId() , HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
//hack to prevent sticking window to the fore
SetWindowPos((HWND)actWin->winId() , HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
}
警告:这是一个仅限 Windows 的解决方案,它可以在我的机器上运行。还要确保在实现中包含 windows.h。
[edit] 我的代码有一个问题,一旦激活,窗口就会停留在最前面。这种黑客可以解决它。
关于c++ - 在 Visual Studio 中的单实例 Qt 应用程序版本 5.11.1 中,在每个其他窗口的顶部打开 Qt MainWindow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52556369/