qt程序只运行一个实例,点击快捷方式置顶窗口

1.在程序的主窗口中设置标题

setWindowTitle("MainWidget"); 

2.在程序的main函数中加入以下代码

// 杀死主进程
void killProcess()
{
    qint64 pid = QCoreApplication::applicationPid();
    QString cmd = QString("TASKKILL /PID %1 /T /F").arg(pid);
    WinExec(cmd.toLocal8Bit().data(), SW_HIDE);
}

// 程序只能运行一个实例
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
// 程序只能运行一个实例
    QSystemSemaphore sys("KoScanCarHMI Key", 1, QSystemSemaphore::Open);
    sys.acquire();

    QSharedMemory shareMemory;
    shareMemory.setKey("KoScanCarHMI App");
    bool isRunning = false;
    if(shareMemory.attach()) {
        isRunning = true;
    } else {
        shareMemory.create(1);
        isRunning = false;
    }
    sys.release();

    if(isRunning) {
        LPCSTR app = TEXT("Qt5QWindowIcon");
        LPCSTR appCaption = TEXT("KoScanCarHMI");

        QString text = "IsWindow";
        HWND hwnd = ::FindWindow(app, appCaption);
        if(::IsWindow(hwnd)) {
            //ShowWindow(hwnd, SW_RESTORE);
            showCenterWindow(hwnd);
            SetForegroundWindow(hwnd);
        }
        killProcess();
    }

    return a.exec();
}

你可能感兴趣的:(qt程序只运行一个实例,点击快捷方式置顶窗口)