2013-12-09 37 views
0

我想結束一個可執行文件(.exe)乳寧我的電腦編程方式使用WPF,我已經贏得成功通過啓動這個.EXE文件:密切.exe文件單擊

if (_MyPath != "") 
{ 
    Process StartApp = new Process(); 
    string str = @_MyPath; 
    StartApp.StartInfo.FileName = str; 
    StartApp.Start(); 
} 
else 
{ 
    MessageBox.Show("Path Empty", "Error", MessageBoxButton.OK, MessageBoxImage.Error); 
} 

現在我的目的是通過點擊一個按鈕來關閉這個.EXE文件的進程?

+0

你需要 發現問題的過程中,一旦發現 - 你殺了。 http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill(v=vs.110).aspx –

+0

@Ahmedilyas OP已經有了對過程對象 –

+0

的引用yup,I re - 讀它並錯過它。抱歉! –

回答

3

存儲流程實例中的一個字段,請調用Process.CloseMainWindowProcess.Kill就可以了。

CloseMainWindow嚮應用程序發送一個窗口關閉消息,該消息讓用戶在關閉之前執行任何所需的操作,甚至可以決定忽略該請求。

另一方面,殺死,要求操作系統直接殺死目標進程,可能會導致數據丟失。它也是一個異步調用,這意味着您必須調用Process.WaitForExit來等待進程結束。

在這兩種情況下,如果目標進程在調用Kill或CloseMainWindow之前終止,或者終止進程或操作系統根本無法終止它,則需要處理可能引發的異常(可能由於安全限制)

爲了避免一些例外,你可以簡單地檢查孩子申請是否試圖殺死它,之前完成致電Process.HasExited

你可以嘗試這樣的事:

Process _childApp; 

private void SpawnProcess() 
{ 
... 
    if (_MyPath != "") 
    { 
     _childApp= new Process(); 
     string str = @_MyPath; 
     _childApp.StartInfo.FileName = str; 
     _childApp.Start(); 
    } 
    else 
    { 
     MessageBox.Show("Path Empty", "Error", MessageBoxButton.OK, 
               MessageBoxImage.Error); 
    } 
... 
} 

private void StopProcess() 
{ 
    if (_childApp.HasExited) 
     return; 
    try 
    { 
     _childApp.Kill(); 
     if (!_childApp.WaitForExit(5000)) 
     { 
      MessageBox.Show("Closing the app takes too long","Warning", 
               MessageBoxButton.OK, 
               MessageBoxImage.Error); 
     } 
    } 
    catch(Exception exc) 
    { 
      MessageBox.Show(exc.ToString(),"Failed to close app", 
               MessageBoxButton.OK, 
               MessageBoxImage.Error); 
    } 
} 
+0

謝謝兄弟:) – user2933082

0
+0

當你已經有一個引用它的時候,沒有必要去搜索這個過程 –

+0

同意@PanagiotisKanavos - 我重新閱讀它,並計算出來。但是,如果他們沒有參考,那麼我正在採取更多的解決方案,那麼這就是你所做的。 –

0

保存過程中的參考,當你想停止它,調用Kill方法:

StartApp.Kill(); 
+0

我不會用kill。 –