2009-11-30 126 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

我需要一個EXECUT LUA腳本... – RCIX 2009-11-30 02:15:54

+0

@RCIX:如何你現在做了嗎?我的意思是手動方式。 – 2009-11-30 02:17:01

+0

即在控制檯命令中放置'blah.lua somearg anotherarg thirdarg'。 – RCIX 2009-11-30 02:17:03

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

如果腳本需要一段時間,您可能需要考慮異步方法。

下面是一些代碼,它可以將標準輸出重定向到捕獲以便在表單上顯示(WPF,Windows Forms,無論如何)。請注意,我假設你並不需要用戶輸入,所以它不創建控制檯窗口,它看起來更好:

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

正確使用後臺工作人員並且不會阻塞整個線程。更好的用戶體驗! – ppumkin 2013-02-10 16:06:42