问题描述
我想要实现的目标(并且正在努力)基本上是通过QT Mainwindow应用程序将命令传递给CMD。
What I'm trying to achieve (And struggling with) is basically passing commands to CMD through my QT Mainwindow application.
我想要我的代码,首先运行CMD(最好是隐藏的)。我在这里使用QProcess是这样的:
I would like to have my code, first run CMD (preferably hidden). I used here QProcess like this:
(在我的 Mainwindow.cpp 文件中)
QString exePath = "C:/Windows/System32/cmd.exe";
QProcess pro;
pro.startDetached(exePath);
pro.waitForStarted();
,一个明显的问题是您使用的是 static
方法 startDetached()
和 blocking 函数 waitForFinished()
... QProcess :: waitForStarted()
/ waitForFinished()
不会捕获来自分离 QProcess的信号;
因此,您可以使用:
If you looked at this post, one apparent problem is that you are using the static
method startDetached()
with the blocking function waitForFinished()
... QProcess::waitForStarted()
/waitForFinished()
won't catch signals from detached QProcess;Thus you could use:
QProcess pro;
pro.start(exePath);
pro.waitForStarted(); // the correct is `waitForStarted()`
fstream 不清楚-对我来说-在您的描述中,您希望用户向您的进程发送 command :
那么,例如,是:
What your trying to do with fstream
is not clear - to me - while in your description, you want user to send a command to your process:then this could, for instance, be :
QByteArray user_cmd = QVariant(ui->lineEdit_command->text()).toByteArray();
pro.write(user_cmd);
pro.write("\n\r"); // press Enter to execute the command
因此您的代码可能是:
#include <QProcess>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void readResult();
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
QProcess* pro;
};
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QString>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::on_pushButton_clicked);
QString exePath = "C:/Windows/System32";
pro = new QProcess(parent);
pro->setWorkingDirectory(exePath);
pro->setReadChannel(QProcess::StandardOutput);
connect(pro,&QProcess::readyReadStandardOutput, this, &MainWindow::readResult);
pro->start("cmd.exe");
if (!pro->waitForStarted())
{
qDebug() << "The process didnt start" << pro->error();
}
}
void MainWindow::on_pushButton_clicked()
{
if (ui->lineEdit_command->text().isEmpty())
return;
QByteArray cmd = QVariant(ui->lineEdit_command->text()).toByteArray();
pro->write(cmd);
pro->write("\n\r");
ui->lineEdit_command->clear();
}
void MainWindow::readResult()
{
while(pro->bytesAvailable()){
QString dirout = pro->readLine();
qDebug() << dirout;
}
}
MainWindow::~MainWindow()
{
delete ui;
}
这篇关于通过Qt GUI将命令传递/提供给CMD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!