技术开发 频道

利用BackgroundWorker检测网络连接

public InternetConnection(IContainer container)
        {
            container.Add(
this);
            InitializeComponent();
            bgworker
= new BackgroundWorker();
            bgworker.WorkerReportsProgress
= false;
            bgworker.WorkerSupportsCancellation
= false;
            bgworker.DoWork
+= new DoWorkEventHandler(this.BackgroundWorker_DoWork);
            bgworker.RunWorkerCompleted
+= new RunWorkerCompletedEventHandler(this.BackgroundWorker_RunWorkerCompleted);
        }

  组件创建完,全部编译下整个解决方案,打开最初创建的项目WindowsFormsApplication1的窗体Form1,我们会在VS IDE中的工具箱中发现我们刚刚创建的名为InternetConnection组件,将其拖到Form1窗体上,便有了其类型的实例internetConnection1。在窗体上我们放置一个Button、一个WebBrowser和一个StatusStrip,并且在StatusStrip中添加一个StatusLabel。我们利用WebBrowser显示一个特定网页,来表示Internet连接可用。

  选中 internetConnection1 我们会发现其公开了两个事件,我们为这两事件添加相应处理代码:

private void internetConnection1_Connected(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Image
= Properties.Resources.Online;
            toolStripStatusLabel1.Text
= "已连接到 Internet,正在打开 it168.com 网页....";
            webBrowser1.Navigate(
"http://www.it168.com/");
        }

        
private void internetConnection1_ConnectFailure(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Image
= Properties.Resources.Offline;
            toolStripStatusLabel1.Text
= "未连接到 Internet";
            webBrowser1.Navigate(Application.StartupPath
+ "\\Error.html");
        }
0
相关文章