HOW TO:使用 Visual Basic .NET 關閉另一個應用程式

文章翻譯 文章翻譯
文章編號: 305602 - 檢視此文章適用的產品。
本文曾發行於 CHT305602
全部展開 | 全部摺疊

在此頁中

結論

本文將告訴您如何從某應用程式內關閉某應用程式。文中也說明了如果另一個應用程式 (例如「記事本」) 有多個執行個體正在執行,要如何關閉此應用程式的某特定執行個體。

程式邏輯討論

宣告變數

有許多變數必須先定義。由於這些變數會用在數個方法內,因此必須在程序外部定義,以便保持位於範圍之內。 proc 變數中存有對個別處理物件的參考, processes 則是存放 GetProcessByName 方法所傳回的處理物件的陣列:
Private proc As Process
Private processes() As Process
Private procName As String = "notepad"

取得應用程式執行個體的清單

下面程式碼包含一個函式 (在此範例中稱為 buildList ),每次建立一個記事本執行個體時就會呼叫此函式。此範例將處理資訊儲存在 ListView 控制項中;含括用來填入 (Populate) ListView 控制項的程式碼只是為了與完整的範例一致。此程式碼最重要的部份是對 Process 類別的 GetProcessByName 方法的呼叫。此方法會傳回 Process 物件的陣列,您可以使用 For ... Each 區塊來一再重複此陣列,如下所示:
Dim itemAdd As ListViewItem
ListView1.Items.Clear()

processes = Process.GetProcessesByName(procName)

For Each proc In processes
    itemAdd = ListView1.Items.Add(proc.MainWindowTitle)
    itemAdd.SubItems.Add(proc.Id.ToString)
Next

關閉應用程式的某特定執行個體

如果某個應用程式有多個執行個體正在執行,而您想關閉其中一個執行個體,就必須先將這些處理序區別開來。以下範例使用了 Process 物件的 Id 屬性來區分這些處理序。 Id 屬性和 MainWindowTitle 屬性 ( Process 物件的另一個屬性) 會儲存在 ListView 控制項中。此程式碼會取得 ListView 控制項中目前選取的項目,使用 Process 類別的 GetProcessById 方法取得處理序的參考,然後呼叫 CloseMainWindow 方法來關閉該處理序,如下所示:
Try
    Dim procID As Integer = _  
     System.Convert.ToInt32(ListView1.SelectedItems(0).SubItems(1).Text)
    Dim tempProc As Process = Process.GetProcessById(procID)
    tempProc.CloseMainWindow()
    tempProc.WaitForExit()
    buildList()
Catch
    MessageBox.Show("Please select a process in the ListView before clicking this button." + _
      " Or the Process may have been closed by somebody.")
    buildList()
End Try

關閉應用程式的所有執行個體

相較之下,關閉特定應用程式的所有執行個體就直接多了。您可以引導 GetProcessByName 方法所傳回的陣列,並呼叫每一個處理序物件的 CloseMainWindow 方法,如下所示:
Try
  For Each proc In processes
    proc.CloseMainWindow()
    proc.WaitForExit()
  Next
  buildList()
Catch ex As System.NullReferenceException
  MessageBox.Show("No instances of Notepad running.")      
End Try

範例的建置步驟

  1. 在 Visual Studio .NET 中新建一個 Visual Basic Windows 應用程式。
  2. 以滑鼠右鍵按一下預設表單 Form1.vb,然後選取 [檢視程式碼]
  3. 以下列程式碼取代程式碼視窗中的內容:
    Option Strict On
    Option Explicit On 
    
    Public Class Form1
      Inherits System.Windows.Forms.Form
    
    #Region " Windows Form Designer generated code "
    
      Public Sub New()
        MyBase.New()
    
        'This call is required by the Windows Form Designer.
        InitializeComponent()
    
        'Add any initialization after the InitializeComponent() call.
    
      End Sub
    
      'Form overrides dispose to clean up the component list.
      Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
          If Not (components Is Nothing) Then
            components.Dispose()
          End If
        End If
        MyBase.Dispose(disposing)
      End Sub
      Friend WithEvents btnLaunch1 As System.Windows.Forms.Button
      Friend WithEvents ColumnHeader1 As System.Windows.Forms.ColumnHeader
      Friend WithEvents ColumnHeader2 As System.Windows.Forms.ColumnHeader
      Friend WithEvents ListView1 As System.Windows.Forms.ListView
      Friend WithEvents btnCloseAll As System.Windows.Forms.Button
      Friend WithEvents btnClose1 As System.Windows.Forms.Button
    
      'Required by the Windows Form Designer.
      Private components As System.ComponentModel.Container
    
      'NOTE: The following procedure is required by the Windows Form Designer
      'It can be modified by using the Windows Form Designer.  
      'Do not modify it by using the code editor.
      <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.btnClose1 = New System.Windows.Forms.Button()
        Me.ListView1 = New System.Windows.Forms.ListView()
        Me.ColumnHeader1 = New System.Windows.Forms.ColumnHeader()
        Me.ColumnHeader2 = New System.Windows.Forms.ColumnHeader()
        Me.btnCloseAll = New System.Windows.Forms.Button()
        Me.btnLaunch1 = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        '
        'btnClose1
        '
        Me.btnClose1.Location = New System.Drawing.Point(160, 176)
        Me.btnClose1.Name = "btnClose1"
        Me.btnClose1.Size = New System.Drawing.Size(112, 32)
        Me.btnClose1.TabIndex = 4
        Me.btnClose1.Text = "Close Selected Process"
        '
        'ListView1
        '
        Me.ListView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.ColumnHeader1, Me.ColumnHeader2})
        Me.ListView1.Location = New System.Drawing.Point(22, 8)
        Me.ListView1.MultiSelect = False
        Me.ListView1.Name = "ListView1"
        Me.ListView1.Size = New System.Drawing.Size(250, 152)
        Me.ListView1.TabIndex = 7
        Me.ListView1.View = System.Windows.Forms.View.Details
        '
        'ColumnHeader1
        '
        Me.ColumnHeader1.Text = "Window Title"
        Me.ColumnHeader1.Width = 160
        '
        'ColumnHeader2
        '
        Me.ColumnHeader2.Text = "Process ID"
        Me.ColumnHeader2.Width = 85
        '
        'btnCloseAll
        '
        Me.btnCloseAll.Location = New System.Drawing.Point(160, 216)
        Me.btnCloseAll.Name = "btnCloseAll"
        Me.btnCloseAll.Size = New System.Drawing.Size(112, 32)
        Me.btnCloseAll.TabIndex = 3
        Me.btnCloseAll.Text = "Close All Processes"
        '
        'btnLaunch1
        '
        Me.btnLaunch1.Location = New System.Drawing.Point(32, 176)
        Me.btnLaunch1.Name = "btnLaunch1"
        Me.btnLaunch1.Size = New System.Drawing.Size(112, 72)
        Me.btnLaunch1.TabIndex = 1
        Me.btnLaunch1.Text = "Start Notepad"
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 266)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.ListView1, Me.btnClose1, Me.btnCloseAll, Me.btnLaunch1})
        Me.Name = "Form1"
        Me.Text = "Process Example"
        Me.ResumeLayout(False)
    
      End Sub
    
    #End Region
    
      Private procName As String = "notepad"
      Private proc As Process
      Private processes() As Process
      Private specialFolder As String = System.Environment.GetFolderPath(Environment.SpecialFolder.System)
    
      Private Sub buildList()
        'this sub populates the listview control with the instances of 'procName'
        'that are currently running.
        Dim itemAdd As ListViewItem
        ListView1.Items.Clear()
    
        processes = Process.GetProcessesByName(procName)
    
        For Each proc In processes
          itemAdd = ListView1.Items.Add(proc.MainWindowTitle)
          itemAdd.SubItems.Add(proc.Id.ToString)
        Next
    
      End Sub
    
    
      Private Sub btnLaunch1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLaunch1.Click
        'Launch notepad and open the end user license agreement.
        Dim pInfo As New ProcessStartInfo()
        pInfo.FileName = specialFolder & "\eula.txt"
        pInfo.WindowStyle = ProcessWindowStyle.Minimized
        Dim p As Process = Process.Start(pInfo)
        p.WaitForInputIdle()
        buildList()
      End Sub
    
    
      Private Sub btnClose1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose1.Click
        'Close one of the instances of notepad based on the selected item in the ListView.
        'There are several ways to identify a process. For example,
        'you can use the mainwindowtitle, windowhandle, or processname, depending  
        'on your needs. The process ID is used here because there may be several
        'windows open with the same title.
        Try
          Dim procID As Integer = System.Convert.ToInt32(ListView1.SelectedItems(0).SubItems(1).Text)
          Dim tempProc As Process = Process.GetProcessById(procID)
          tempProc.CloseMainWindow()
          tempProc.WaitForExit()
          buildList()
        Catch
          MessageBox.Show("Please select a process in the ListView before clicking this button." + _
          " Or the Process may have been closed by somebody.")
          buildList()
        End Try
      End Sub
    
      Private Sub btnCloseAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCloseAll.Click
        'Walk the process array and close all processes.
        Try
          For Each proc In processes
            proc.CloseMainWindow()
            proc.WaitForExit()
          Next
          buildList()
        Catch ex As System.NullReferenceException
          MessageBox.Show("No instances of Notepad running.")      
        End Try
      End Sub
    
      Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        'Make sure that you do not leave any instances running.
        If Not (processes Is Nothing) Then
          If (processes.Length <> 0) Then
            Me.btnCloseAll_Click(Me, e)
          End If
        End If
      End Sub
    
    End Class
    注意 :建議您將標示為 [Windows Form 設計工具產生的程式碼] 的區域摺疊起來。
  4. :建議您將標示為 執行此應用程式。
  5. :建議您將標示為 按一下或多下 [啟動記事本]
  6. :建議您將標示為 在 [ListView] 控制視窗中按一下記事本的某個執行個體,然後選取 [關閉處理序] 。如此即可關閉您所選取的特定記事本執行個體。您也可以選取 [關閉所有處理序] 來關閉執行中的所有記事本執行個體。

注意

這個範例使用 Process 類別的 Id 屬性來區分應用程式的各個執行個體。 Id 屬性非常適合用在這項作業上,因為所有處理序識別碼都是獨一無二的。 WindowHandle 屬性也一樣,因此您也可以使用某個 Process 物件的 WindowHandle 屬性來區別應用程式的各個執行個體。

其他屬性雖然不那麼適合用在這項作業上,但亦可使用。例如,若不知道特定處理序的處理序識別碼或者您有主視窗的控制代碼,即可使用 MainWindowTitle 屬性來協助辨識正確的執行個體。 MainWindowTitle 屬性可能不是唯一的,但它能協助您隔離出所要的應用程式。

本文範例是使用 Windows 應用程式並採用 CloseMainWindow 方法來關閉應用程式。 CloseMainWindow 無法用在非 Windows 應用程式上。若欲關閉的應用程式沒有視窗 (例如主控台應用程式),您必須使用 Kill 方法來關閉應用程式。

參考

如需詳細資訊,請參閱以下的 Microsoft Developer Network (MSDN) 網站:
Process Class
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemDiagnosticsProcessClassTopic.asp


本文件是根據 Microsoft Knowledge Base 文件編號 Q305602 翻譯的。若要參考原始英文文件內容,請至以下網址:

http://support.microsoft.com/support/kb/articles/Q305/6/02.asp

屬性

文章編號: 305602 - 上次校閱: 2002年2月15日 - 版次: 1.0
這篇文章中的資訊適用於:
  • Microsoft Visual Basic .NET 2002 Standard Edition
關鍵字:?
kbhowto kbhowtomaster KB305602
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。

提供意見

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com