代码之家  ›  专栏  ›  技术社区  ›  Narendra Prasath

在Visual Studio的单实例Qt应用程序版本5.11.1中打开Qt主窗口

  •  0
  • Narendra Prasath  · 技术社区  · 6 年前

    Visual Studio . 一旦它第一次执行,我的主窗口将打开,我关闭它。它一直在后台运行。

    我正在枚举可用的windows标题 头衔。但是用这个 我正试着用 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主窗口 当我第二次运行的时候。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Max Lambertini    6 年前

    签出在中找到的项目QtSingleApplication https://github.com/qtproject/qt-solutions .

    在QtSingleApplication类中有一个名为 . 在 装载机

    若要在尝试打开第二个实例时使主窗口位于顶部,必须像这样修改此方法。

    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专用的解决方案,它可以在我的机器上运行。也一定要包括 窗口.h 在实施中。

    [编辑]我的代码有一个问题,一旦激活,窗口就一直保持在最前面。这个黑客可以解决这个问题。