Tuesday, January 22, 2008

Ứng dụng C# gọi chương trình console mà không xuất hiện cửa sổ DOS

Trong quá trình lập trình, tôi sử dụng đến một chương trình DOS để thực hiện các tác vụ nền, vì là tác vụ nền nên không muốn nó hiển thị lên cửa sổ đen của DOS khi nó được gọi. Sau đây là cách thực hiện (môi trường C#):
// This code needs the "System.Diagnostics" library
// Application path and command line arguments
string ApplicationPath = "C:\\example.exe";
string ApplicationArguments = "-c -x";
// Create a new process object
Process ProcessObj = new Process();
// StartInfo contains the startup information of the new process
ProcessObj.StartInfo.FileName = ApplicationPath;
ProcessObj.StartInfo.Arguments = ApplicationArguments;
// These two optional flags ensure that no DOS window appears
ProcessObj.StartInfo.UseShellExecute = false;
ProcessObj.StartInfo.CreateNoWindow = true;
// If this option is set the DOS window appears again :-/
// ProcessObj.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// This ensures that you get the output from the DOS application
ProcessObj.StartInfo.RedirectStandardOutput = true;
// Start the process
ProcessObj.Start();
// Wait that the process exits
ProcessObj.WaitForExit();
// Now read the output of the DOS application
string Result = ProcessObj.StandardOutput.ReadToEnd();

No comments:

Post a Comment