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