简体   繁体   中英

How to bring a qprocess to the front?

Working Env: C++, window I opened a matlab standalone application(xx.exe) using qprocess. When user press a button, I want to bring xx.exe to the front. How can I bring xx.exe to the front using Qprocess?

Maybe QProcess::startDetached() will help you (in my case this method activates window). But window manipulation (like activate , minimize , hide ) is OS issue I think. So in most cases you have to request OS for window manipulation.

Here is a small example for Windows you can try

WindowsUtils.h

class WindowsUtils
{
public:
    WindowsUtils();

    static bool ShowWindow(const qint64& pidQt);
    static bool MinimizeWindow(const qint64& pidQt);
    static bool RestoreWindow(const qint64& pidQt);
};

WindowsUtils.cpp

#include "WindowsUtils.h"
#include <windows.h>

int g_winState = SW_SHOW;

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
    // get the window process ID
    DWORD searchedProcessId = (DWORD)lParam;
    DWORD windowProcessId = 0;
    GetWindowThreadProcessId(hWnd,&windowProcessId);

    // check the process id match
    if (windowProcessId == searchedProcessId){
        ShowWindow(hWnd, g_winState);
        return FALSE;
    }

    return TRUE;  //continue enumeration
}

WindowsUtils::WindowsUtils()
{

}

bool WindowsUtils::ShowWindow(const qint64 &pidQt)
{
    g_winState = SW_SHOW;
    return EnumWindows(EnumWindowsProc, (LPARAM)pidQt);
}

bool WindowsUtils::MinimizeWindow(const qint64 &pidQt)
{
    g_winState = SW_MINIMIZE;
    return EnumWindows(EnumWindowsProc, (LPARAM)pidQt);
}

bool WindowsUtils::RestoreWindow(const qint64 &pidQt)
{
    g_winState = SW_RESTORE;
    return EnumWindows(EnumWindowsProc, (LPARAM)pidQt);
}

Using

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:

    void on_pushButton_3_clicked();

    void on_pushButton_4_clicked();

    void on_pushButton_5_clicked();

private:
    Ui::MainWindow *ui;
    qint64 m_pid;
};

void MainWindow::on_pushButton_3_clicked()
{
    m_pid = 0;
    QProcess::startDetached("notepad.exe", QStringList(), QString(), &m_pid);
}

void MainWindow::on_pushButton_4_clicked()
{
    WindowsUtils::RestoreWindow(m_pid);
}

void MainWindow::on_pushButton_5_clicked()
{
    WindowsUtils::MinimizeWindow(m_pid);
}

Another values for int g_winState; you find here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM