HOW TO:使用 C# 检测应用程序是否已停止响应 (From MSDN)

时间:2024-02-25 20:26:01

本文的发布号曾为 CHS304991
本文讨论一种 Microsoft 产品的 Beta 版本。本文中的信息按"原样"提供,如有更改恕不另行通知。

对于该 Beta 产品,Microsoft 不提供正式的产品支持。有关获取对 Beta 版本的支持的信息,请参阅 Beta 产品文件中包括的文档资料,或查看您下载此版本的站点。
本任务的内容
概要
启动应用程序 确定应用程序是否响应 关闭应用程序

关于该示例 生成该示例的步骤


参考
概要
在某些情况下,您可能需要检测应用程序是否被阻塞。例如,在 Microsoft Internet Explorer 自动运行时,您可能想知道 Internet Explorer 是否已停止响应。

本文描述如何检测 Internet Explorer 的自动实例是否已停止响应(挂起)以及如何关闭 Internet Explorer。尽管此代码是针对 Internet Explorer 和 Visual C# .NET 而编写的,您也可以将此办法用于其他应用程序。

本文的前三节概述完成此任务所必需的三个重要的编码概念。第四节演示如何生成示例应用程序。

返回页首
启动应用程序
本文的示例将 Internet Explorer 用作测试应用程序。下面的代码启动 Internet Explorer 并使用 GetProcessByName 方法获取该进程的句柄。
   Browser = new InternetExplorer();
   Browser.Visible = true;
   Browser.GoHome();
   procs = Process.GetProcessesByName("IEXPLORE");返回页首
确定应用程序是否响应
下面的代码检查 GetProcessByName 方法返回的 procs 数组中的第一个元素,以确定进程是否响应。本文假定只运行一个 Internet Explorer 实例。
    if (Browser!=null)
        if (procs[0].Responding ) 
     MessageBox.Show("IEXPLORE is Responding");
 else
     MessageBox.Show("IEXPLORE is Not Responding");
    else
 MessageBox.Show("IEXPLORE is Not Running");返回页首
关闭应用程序
下面的代码演示如何关闭应用程序。如果应用程序仍然响应,则可以使用 Process 类的 CloseMainWindows 方法关闭它。如果应用程序不响应,则必须调用 Kill 方法。必须使用 try-catch 程序块来处理因进程不存在而出现的异常。
    try
        {
        if (procs[0].Responding)
            procs[0].CloseMainWindow();
        else
     procs[0].Kill();
 }
    catch
 {
 MessageBox.Show("Could Not Find the IEXPLORE Process");
 }
返回页首
生成示例项目
关于该示例
本文中的示例项目由包含以下三个按钮的窗体组成:
启动 Internet Explorer,使用"自动化"启动一个 Internet Explorer 实例。
检查 Internet Explorer,测试浏览器是否响应。
关闭 Internet Explorer,关闭浏览器。
如果想对代码进行彻底测试,了解会导致浏览器停止响应的 Web 页的情况,您可以在打开浏览器后浏览该页。然后,尝试单击检查 Internet Explorer 和关闭 Internet Explorer。单击这些按钮后稍作等待;如果浏览器不响应,则不会立即出现响应。 返回页首
生成示例的步骤
在 Visual Basic .NET 中开始一个新的 Windows C# 应用程序。
在解决方案资源管理器窗口中,右键单击引用,然后单击添加引用。
在添加引用对话框中的 COM 选项卡上,单击 Microsoft Internet Controls,然后单击选择。
单击确定以关闭添加引用对话框。 备注:如果看到下面的对话框,请单击是以创建所需的包装:

Could not find a primary interop assembly for the COM component \'Microsoft Internet Controls\'.A primary interop assembly is not registered for this type library.Would you like to have a wrapper generated for you?(找不到 COM 组件"Microsoft Internet Controls"的主 interop 程序集。未为此类型库注册 interop 程序集。希望生成一个包装吗?)
如果未看到此对话框,则可能是您已经有了必需的 interop 包装。


:如果看到下面的对话框,请单击在解决方案资源管理器窗口中,右键单击 Form1.cs,然后单击查看代码。
:如果看到下面的对话框,请单击删除 Form1.cs 代码窗口中的所有代码。
:如果看到下面的对话框,请单击将下列代码粘贴到 Form1.cs 代码窗口中:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using SHDocVw;
using System.Diagnostics;
namespace appStoppedresponding_cs
{
  public class Form1 : System.Windows.Forms.Form
  {
    private System.Windows.Forms.Button btnStart;
    private System.Windows.Forms.Button btnCheck;
    private System.Windows.Forms.Button btnClose;
   
    private System.ComponentModel.Container components = null;

    private  InternetExplorer Browser;
    protected Process[] procs;
   
    public Form1()
    {
      InitializeComponent();
    }
 
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null)
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }

    #region Windows Form Designer generated code
   
    private void InitializeComponent()
    {
      this.btnCheck = new System.Windows.Forms.Button();
      this.btnStart = new System.Windows.Forms.Button();
      this.btnClose = new System.Windows.Forms.Button();
      this.SuspendLayout();
      //
      // btnCheck
      //
      this.btnCheck.Location = new System.Drawing.Point(66, 122);
      this.btnCheck.Name = "btnCheck";
      this.btnCheck.Size = new System.Drawing.Size(152, 23);
      this.btnCheck.TabIndex = 1;
      this.btnCheck.Text = "Check Internet Explorer";
      this.btnCheck.Click += new System.EventHandler(this.btnCheck_Click);
      //
      // btnStart
      //
      this.btnStart.Location = new System.Drawing.Point(66, 74);
      this.btnStart.Name = "btnStart";
      this.btnStart.Size = new System.Drawing.Size(152, 23);
      this.btnStart.TabIndex = 0;
      this.btnStart.Text = "Start Internet Explorer";
      this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
      //
      // btnClose
      //
      this.btnClose.Location = new System.Drawing.Point(66, 170);
      this.btnClose.Name = "btnClose";
      this.btnClose.Size = new System.Drawing.Size(152, 23);
      this.btnClose.TabIndex = 2;
      this.btnClose.Text = "Close Internet Explorer";
      this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
      //
      // Form1
      //
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(292, 266);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.btnClose,
                                      this.btnCheck,
                                      this.btnStart});
      this.Name = "Form1";
      this.Text = "Form1";
      this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
      this.Load += new System.EventHandler(this.Form1_Load);
      this.ResumeLayout(false);

    }
    #endregion

    //example code
    /// The main entry point for the application.
    [STAThread]
    static void Main()
    {
      Application.Run(new Form1());
    }
   
    private void btnStart_Click(object sender, System.EventArgs e)
    {
      Browser = new InternetExplorer();
      Browser.Visible = true;
      Browser.GoHome();
      procs = Process.GetProcessesByName("IEXPLORE");
      //Build event delegate to catch browser close event.
      SHDocVw.DWebBrowserEvents2_OnQuitEventHandler oDelegate = new
        SHDocVw.DWebBrowserEvents2_OnQuitEventHandler(Browser_OnQuit);
           Browser.OnQuit += oDelegate;
    }

    private void btnCheck_Click(object sender, System.EventArgs e)
    {
      if (Browser!=null)
     
        if (procs[0].Responding ) 
          MessageBox.Show("IEXPLORE is Responding");
        else
          MessageBox.Show("IEXPLORE is Not Responding");
      else
        MessageBox.Show("IEXPLORE is Not Running");
               
      }

    private void btnClose_Click(object sender, System.EventArgs e)
    {
      this.closeBrowser();
    }

    private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    { //If the browser is still open, close it when the form closes.
      if (Browser!=null)
        this.closeBrowser();
    }
    private void closeBrowser()
    {
      try
      {
        if (procs[0].Responding)
          procs[0].CloseMainWindow();
        else
          procs[0].Kill();
        //Destroy object reference and array.
        this.cleanUp();
      }
      catch
      {
        MessageBox.Show("Could Not Find the IEXPLORE Process");
      }
    }
    private void Browser_OnQuit()
    { //event delegate - clean up if the browser is closed manually 
      this.cleanUp();
    }
    private void cleanUp()
    {  //Destroy browser reference variable and array.
      Browser = null;
      procs=null;
    }

    private void Form1_Load(object sender, System.EventArgs e)
    {/*required method*/}
  }

}备注:上面的代码在窗体上自动绘制、定位和命名三个按钮,因此您不必手动添加它们。
:如果看到下面的对话框,请单击在将此代码粘贴到 Form1.cs 代码窗口后,您可能希望将标为"Windows Form Designer generated code "的区域折叠起来。
:如果看到下面的对话框,请单击按 F5 键生成和运行该项目。
:如果看到下面的对话框,请单击在 Internet Explorer 运行时,单击窗体上的按钮可测试这些代码。

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/wukong777/archive/2004/10/09/129302.aspx