我需要cmd在 c# 中啟動一個命令,例如:Echo Test.
接下來我想CMD在這樣的訊息框中顯示輸出:
MessageBox.Show(output_of_cmd_command);
可能嗎?如果是這樣,怎么做?
uj5u.com熱心網友回復:
這將包括幾個步驟:
- 使用正確的引數啟動 CMD 行程
- 捕獲 CMD 輸出
- 在訊息框中顯示
我最近通過使用這個函式為 Python 做了一些事情:
請記住,我通過設定UseShellExecute和明確抑制了 CMD 對話框本身CreateNoWindow。如果你喜歡你可以改變這些。
private string RunCommand(string fileName, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = fileName;
start.Arguments = string.Format("{0}", args);
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
start.UseShellExecute = false;
start.CreateNoWindow = true;
var sb = new StringBuilder();
using (Process process = new Process())
{
process.StartInfo = start;
process.OutputDataReceived = (sender, eventArgs) =>
{
sb.AppendLine(eventArgs.Data); //allow other stuff as well
};
process.ErrorDataReceived = (sender, eventArgs) => {
};
if (process.Start())
{
process.EnableRaisingEvents = true;
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
//allow std out to be flushed
Thread.Sleep(100);
}
}
return sb.ToString();
}
用法:
var result = RunCommand("path to your cmd.exe", "/C c:\example.bat");
MessageBox.Show(result);
以下是 CMD 選項的串列:
Starts a new instance of the Windows command interpreter
CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
[[/S] [/C | /K] string]
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
/S Modifies the treatment of string after /C or /K (see below)
/Q Turns echo off
/D Disable execution of AutoRun commands from registry (see below)
/A Causes the output of internal commands to a pipe or file to be ANSI
/U Causes the output of internal commands to a pipe or file to be
Unicode
/T:fg Sets the foreground/background colors (see COLOR /? for more info)
/E:ON Enable command extensions (see below)
/E:OFF Disable command extensions (see below)
/F:ON Enable file and directory name completion characters (see below)
/F:OFF Disable file and directory name completion characters (see below)
/V:ON Enable delayed environment variable expansion using ! as the
delimiter. For example, /V:ON would allow !var! to expand the
variable var at execution time. The var syntax expands variables
at input time, which is quite a different thing when inside of a FOR
loop.
/V:OFF Disable delayed environment expansion.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/455893.html
上一篇:樣式化組件獲得期望Unicode轉義序列\uXXXX
下一篇:Vue復選框子級和父級
