你目前正处于脱机状态,正在等待 Internet 重新连接

HOW TO: 使用 Visual Basic .Net 关闭另一个应用程序

本文的发布号曾为 CHS305602
有关本文的 Microsoft Visual C# .NET 版本,请参阅 CHS305603


本任务的内容


概要
本文介绍如何在一个应用程序内关闭另一个应用程序。 本文还介绍在另一个应用程序(如“记事本”)有多个实例运行的情况下如何关闭其特定实例。

返回页首

对编程逻辑的讨论

声明变量

需要定义多个变量。 由于在多个方法中使用这些变量,因此应在任何过程外对它们进行定义以使它们保持在范围内。 proc 变量保存对单个进程对象的引用,而 processes 是保存由 GetProcessByName 方法返回的进程对象的数组:
Private proc As ProcessPrivate processes() As ProcessPrivate procName As String = "notepad"

获取应用程序实例列表

下面的代码包含一个函数(在本例中叫做 buildList),每次创建“记事本”的一个新实例时都会调用该函数。 此示例将进程信息存储在 ListView 控件中,之所以包含填充 ListView 控件的代码,只是为了与完整的示例保持一致。 此代码的最重要部分是对 Process 类的 GetProcessByName 方法的调用。 此方法返回 Process 对象的数组,该数组可以通过 For ... Each 块进行迭代,如下所示:
Dim itemAdd As ListViewItemListView1.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 控件中。 该代码通过使用 Process 类的 GetProcessById 方法获取 ListView 控件中当前选中的项,获取对该进程的引用,并通过调用 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 OnOption Explicit On Public Class Form1Inherits 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 ThenIf Not (components Is Nothing) Thencomponents.Dispose()End IfEnd IfMyBase.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.ListViewFriend 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 ProcessPrivate 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)NextEnd 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.MinimizedDim 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 TryEnd 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 TryEnd 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 IfEnd IfEnd SubEnd Class
    备注: 建议将标为 Windows Form Designer generated code 的区域折叠起来。
  4. : 建议将标为运行该应用程序。
  5. : 建议将标为单击 Start Notepad(启动记事本)一次或多次。
  6. : 建议将标为在 ListView 控件窗口单击记事本的一个实例并选择 Close Process(关闭进程)。 这就会关闭您选择的记事本的特定实例。 还可以选择 Close All Processes(关闭所有进程)以关闭记事本的所有正在运行的实例。

备注

本示例使用 Process 类的 Id 属性来区分应用程序的不同实例。 Id 属性是执行此任务的好选择,因为所有进程 ID 都是唯一的。 WindowHandle 属性也是执行此任务的好选择,因此也可以使用 Process 对象的 WindowHandle 属性来区分应用程序的不同实例。

尽管其他属性不太适合执行此任务,但也可以使用这些属性。 例如,如果您不知道特定进程的进程 ID 或没有主窗口的句柄,则可以使用 MainWindowTitle 属性帮助识别适当的实例。 MainWindowTitle 属性可能不是唯一的,但它可以帮助您查出所需要的应用程序。

本文中的示例使用 Windows 应用程序并使用 CloseMainWindow 方法关闭应用程序。 CloseMainWindow 不适用于非 Windows 应用程序。 如果您试图关闭的应用程序没有窗口(例如,控制台应用程序),则必须使用 Kill 方法来关闭应用程序。

返回页首

参考

有关更多信息,请访问下面的 Microsoft Developer Network (MSDN) Web 站点: 返回页首
属性

文章 ID:305602 - 上次审阅时间:02/15/2002 14:59:00 - 修订版本: 1.0

Microsoft Visual .NET 2002 标准版

  • kbhowto kbhowtomaster KB305602
反馈
'meta');m.name='ms.dqp0';m.content='true';document.getElementsByTagName('head')[0].appendChild(m);" onload="var m=document.createElement('meta');m.name='ms.dqp0';m.content='false';document.getElementsByTagName('head')[0].appendChild(m);" src="http://c1.microsoft.com/c.gif?">