2009-11-30 8 views

答えて

9
System.Diagnostics.Process p = new System.Diagnostics.Process(); 
p.StartInfo.FileName = "blah.lua arg1 arg2 arg3"; 
p.StartInfo.UseShellExecute = true; 
p.Start(); 

もう一つの方法は、P/Invokeを使用し、直接のShellExecuteを使用することです:

[DllImport("shell32.dll")] 
static extern IntPtr ShellExecute(
    IntPtr hwnd, 
    string lpOperation, 
    string lpFile, 
    string lpParameters, 
    string lpDirectory, 
    ShowCommands nShowCmd); 
+0

... – RCIX

+0

@RCIX:私はそれが良いに見えるコンソールウィンドウを作成しないように、あなたは、ユーザー入力を必要としないと仮定していることに注意してくださいどのようにあなたは今それをやりましたか?手動で私が意味する方法。 –

+0

、つまりコンソールコマンドに 'blah.lua somearg anotherarg thirdarg'を置くことです。 – RCIX

2

をC#でこれを処理する簡単な方法があります。 System.Diagnostics名前空間を使用すると、産卵プロセスを処理するクラスがあります。

System.Diagnostics.Process process = new System.Diagnostics.Process(); 
process.StartInfo.FileName = "App.exe"; 
process.StartInfo.Arguments = "arg1 arg2 arg3"; 
process.Start(); 

Console.WriteLine(process.StandardOutput.ReadToEnd(); 

コンソールウィンドウの作成や入力や出力のリダイレクトなど、必要なものを処理するための追加パラメータがあります。

6

スクリプトにしばらく時間がかかる場合は、非同期のアプローチを検討してください。

これは、標準出力をフォームに表示するためにキャプチャするようにリダイレクトするコードです(WPFWindows Formsなど)。

私はLuaのスクリプトをステートメする必要が
BackgroundWorker worker = new BackgroundWorker(); 
... 
// Wire up event in the constructor or wherever is appropriate 
worker.DoWork += new DoWorkEventHandler(worker_DoWork); 
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); 
... 
// Then to execute your script 
worker.RunWorkerAsync("somearg anotherarg thirdarg"); 

void worker_DoWork(object sender, DoWorkEventArgs e) 
{ 
    StringBuilder result = new StringBuilder(); 
    Process process = new Process(); 
    process.StartInfo.FileName = "blah.lua"; 
    process.StartInfo.Arguments = (string)e.Argument; 
    process.StartInfo.UseShellExecute = false; 
    process.StartInfo.RedirectStandardOutput = true; 
    process.StartInfo.CreateNoWindow = true; 
    process.Start(); 
    result.Append(process.StandardOutput.ReadToEnd()); 
    process.WaitForExit(); 
    e.Result = result.AppendLine().ToString(); 
} 

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{ 
    if (e.Result != null) console.Text = e.Result.ToString(); 
    else if (e.Error != null) console.Text = e.Error.ToString(); 
    else if (e.Cancelled) console.Text = "User cancelled process"; 
} 
+0

+1バックグラウンドワーカーを適切に使用し、スレッド全体をブロックしない場合は+1。はるかに優れたユーザーエクスペリエンス! – ppumkin

関連する問題