在Qt中隐藏和重新启动相同的QApplication实例
Hiding and relaunching the same instance of QApplication in Qt
我有一个QApplication
,我有一个自定义的QDialog
。对话框为用户提供一组选项,然后通过QProcess
启动一个进程。当启动的进程仍在运行时,关闭的应用程序必须仍在运行。为了实现这一点,我根据进程是否启动,重新实现了QWidget
和accept()
的closeEvent
或ignore()
的事件。
在closeEvent()
函数中,我隐藏了QDialog
。这样,对于用户来说,应用程序将被关闭(但它将在任务管理器中运行)。我希望用户通过再次运行程序来重新启动应用程序。此时,我需要弄清楚另一个实例是否已经在运行,并且该实例应该进入前台。
有谁能告诉我怎么才能做到这一点吗?
命名互斥可以用来解决。
这篇文章很有帮助。WINAPI WinMain(
HINSTANCE, HINSTANCE, LPSTR, int)
{
try {
// Try to open the mutex.
HANDLE hMutex = OpenMutex(
MUTEX_ALL_ACCESS, 0, "MyApp1.0");
if (!hMutex)
// Mutex doesn’t exist. This is
// the first instance so create
// the mutex.
hMutex =
CreateMutex(0, 0, "MyApp1.0");
else
// The mutex exists so this is the
// the second instance so return.
return 0;
Application->Initialize();
Application->CreateForm(
__classid(TForm1), &Form1);
Application->Run();
// The app is closing so release
// the mutex.
ReleaseMutex(hMutex);
}
catch (Exception &exception) {
Application->
ShowException(&exception);
}
return 0;
}
在Qt 5之前,有一个叫做QtSingleApplication的项目,它只允许一个应用程序的一个实例运行,如果用户试图打开另一个实例,将引发正在运行的应用程序。
如果你在Google上搜索"qtsingleapplication qt5",你会发现更多关于qtsingleapplication与qt5一起工作的修复的信息。
相关文章:
- 从C++实例化QML
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 建议在运行时将带有类实例的列表从c++导入qml
- 约束和显式模板实例化
- 完全删除 QApplication 实例并在另一个线程中重新创建它
- 创建真正的无头 QApplication 实例
- 多个 QApplication 实例
- 如何使用线程来实例化多个 QApplication
- 在主函数(库)外部实例化QApplication
- 确定系统是否可以实例化QApplication(GUI支持)
- 在Qt中隐藏和重新启动相同的QApplication实例