.NET 中 System.Diagnostics.Process 類應用中碰到的問題(續)
來源:互聯網
上載者:User
經過一番研究,終於找到了有沒有Word執行個體啟動並執行情況下都能實現上一篇文章中的要求的方法,代碼如下: string tempPath = System.Environment.GetEnvironmentVariable("TEMP");
string fileName = Path.Combine ( tempPath, "推理01.doc");
string winwordPath = "";
// 判斷系統中是否已經有 Word 執行個體在運行。
Process[] wordProcesses = Process.GetProcessesByName("winword");
foreach ( Process process in wordProcesses)
{
Debug.WriteLine( process.MainWindowTitle );
winwordPath = process.MainModule.FileName; // 如果有的話獲得 Winword.exe 的完全限定名稱。
break;
}
Process wordProcess = new Process();
if ( winwordPath.Length > 0 ) // 如果有 Word 執行個體在運行,使用 /w 參數來強制啟動新執行個體,並將檔案名稱作為參數傳遞。
{
wordProcess.StartInfo.FileName = winwordPath;
wordProcess.StartInfo.UseShellExecute = false;
wordProcess.StartInfo.Arguments = fileName + " /w";
}
else // 如果沒有 Word 執行個體在運行,還是
{
wordProcess.StartInfo.FileName = fileName;
wordProcess.StartInfo.UseShellExecute = true;
}
wordProcess.Start();
wordProcess.WaitForExit(); // 當前進程一直在等待,直到該 Word 執行個體退出。
wordProcess.Close();