[英]C# run a batch script without a new window and redirect all (standard/error) output to a RichTextBox
I have a batch script that launches the mariadb in console mode, so it looks likes this: 我有一个在控制台模式下启动mariadb的批处理脚本,因此看起来像这样:
run-mariadb.bat 运行mariadb.bat
@echo off
cd /D mariadb-10.1.14-win32\bin && mysqld.exe --console
@pause
Using a C# WinForm app, I'd like to launch this batch script and get all output onto a RichTextBox. 我想使用C#WinForm应用程序启动此批处理脚本,并将所有输出输出到RichTextBox上。
This is the code I have so far: 这是我到目前为止的代码:
// Configure db server process
Process dbServer = new Process();
dbServer.StartInfo.FileName = "cmd";
dbServer.StartInfo.Arguments = "/c start /wait run-mariadb.bat";
dbServer.StartInfo.CreateNoWindow = true;
dbServer.StartInfo.UseShellExecute = false;
dbServer.StartInfo.RedirectStandardOutput = true;
dbServer.StartInfo.RedirectStandardError = true;
dbServer.OutputDataReceived += new DataReceivedEventHandler(HandleDBServerOutput);
dbServer.ErrorDataReceived += new DataReceivedEventHandler(HandleDBServerOutput);
These are my helper methods: 这些是我的辅助方法:
string FormatOutput(string message)
{
return string.Format("[ {0} ] : {1}",
DateTime.Now.ToShortTimeString(),
message);
}
void HandleDBServerOutput(object sender, DataReceivedEventArgs e)
{
this.BeginInvoke(new MethodInvoker(() =>
{
if (!string.IsNullOrEmpty(e.Data))
dbLogsRTB.AppendText(FormatOutput(e.Data));
}));
}
I start the process like this: 我开始这样的过程:
// Start database server
dbServer.Start();
dbServer.BeginOutputReadLine();
dbServer.WaitForExit();
When the above executes, a new command prompt window is created and the mariadb is running in there. 执行上述操作后,将创建一个新的命令提示符窗口,并且mariadb正在其中运行。 Any ideas why
dbServer.StartInfo.CreateNoWindow = true;
为什么
dbServer.StartInfo.CreateNoWindow = true;
任何想法dbServer.StartInfo.CreateNoWindow = true;
is being ignored? 被忽略?
The help for start
starts off with: start
的帮助始于:
Starts a separate window to run a specified program or command.
启动一个单独的窗口以运行指定的程序或命令。
In other words, by running start
as part of your command, you'll launch a new window. 换句话说,通过将
start
作为命令的一部分运行,您将启动一个新窗口。 You can verify this by running start /wait run-mariadb.bat
from a command prompt. 您可以通过在命令提示符下运行
start /wait run-mariadb.bat
来验证这一点。 It launches a new window to run the command. 它会启动一个新窗口来运行命令。
Consider changing your command to be simply: 考虑将命令更改为简单:
dbServer.StartInfo.Arguments = "/c run-mariadb.bat";
To just run the command without starting a new console process. 仅运行命令而不启动新的控制台进程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.