Preface
Recently, I was writing a gadget for a friend, which involved displaying a command line console. I didn't expect it to be a natural thing, but it became less natural.
Several ways to implement
Method 1 (QProcess)
Implementing it with QProcess was the first way I thought of at the time. Maybe I had been using QProcess to execute the command line before.
I originally thought it could be implemented with one line of code, as shown below. After all, it was possible to use it to call external programs before.
QProcess::execute("cmd.exe");
Then I found that it didn't work. The program (cmd.exe) was running, but no interface was displayed. I searched for a solution to the problem on Baidu and found this qt - QProcess with 'cmd' command does not result in command-line window - Stack Overflow
You need to set parameters through the function setCreateProcessArgumentsModifier to create a new console.
m_pPro->setCreateProcessArgumentsModifier(
[](QProcess::CreateProcessArguments *args) {
args->flags |= CREATE_NEW_CONSOLE;
args->startupInfo->dwFlags &=~ STARTF_USESTDHANDLES;
});
Method 2 (system())
Use the function system() to implement it. I missed that the input parameter of system is a DOS command.
#include<stdlib.h>
system("cmd.exe");
Method three (QDesktopServices::openUrl())
The static function QDesktopServices::openUrl() can open local files, folders, applications or open URLs with the default browser.
//QString path="https://blog.csdn.net/xiaopei_yan?type=blog";
//QString path="C:/Users/admin/Desktop";
QString path="cmd.exe";
QDesktopServices::openUrl(QUrl::fromLocalFile(path));
Method four (CreateProcess())
Windows comes with a method to create a process CreateProcess(). For specific usage, please refer to 19.VC(custom)-CreateProcess function detailed explanation_Hua Xiong's Blog-CSDN Blog
TCHAR szCmdLine[] = { TEXT("cmd.exe") };
STARTUPINFO StartInfo = { sizeof(StartInfo) };
PROCESS_INFORMATION ProcInfo;
StartInfo.dwFlags = STARTF_USESHOWWINDOW;
StartInfo.wShowWindow = TRUE;
CreateProcess(NULL, szCmdLine, NULL, NULL, NULL, NULL, NULL, NULL, &StartInfo, &ProcInfo);
Conclusion
Various methods are available for you to choose from.