需要在一个页面上快捷调用其他程序并且保持状态,需要解决的只有两点。
1、如何调用外部程序
2、调用完程序后如何保持程序状态
当前环境:QT creator 5.9.9 windows10
1、调用外部程序 核心代码
QProcess* caller = new QProcess(this);//创建对象
caller->start("child.exe");//程序路径
Sleep(1000); //这个只能更大,不能更小,不然无法获得子串口句柄,应该和机器性能有关
当我们写完上述程序后,如果我们进行程序的切换,再次切换到child程序的时候我们原先对child程序做的变动是无法生效的。这就引入了下一个问题,如何保持程序状态。
2、保持程序状态
上述问题的原因是我们每次都直接new了一个process去唤醒child程序,当然无法保存。解决办法也很简单,每次调用child程序的时候先判定到底有没有child程序在运行,如果有,直接把child程序调用出来。
判定的核心代码如下:
QProcess process;
process.start("tasklist");
process.waitForFinished();
QByteArray result = process.readAllStandardOutput();
QString str = result;
if(str.contains("child.exe")){
//如果已经运行了child程序
caller->start("child.exe"); //这里不需要加任何路径,因为child程序已经运行了
//do something
}
else{
//如果没有运行child程序
caller->start("C:/child.exe");//程序路径
//do something
}
完整代码在github上:GitHub - torchlegend/composition: qt qprocess parent_child
这个代码也是在另一个代码上修改的,原版本地址:https://github.com/snasoft/qt-windows-composition-example