在标签文本中显示Ping.SendAsync的结果

时间:2015-12-17 03:57:26

标签: c# .net windows winforms

我正在尝试创建ping程序的简单GUI实现。我有一个表单只是一个文本框textBox1,用户输入IP作为字符串,按下按钮Ping,ping的结果显示在标签label1中。出于某种原因,当我运行程序时,文本不会出现。

部分代码来自Ping.SEndAsync

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net.NetworkInformation;
using System.Net;

namespace pinger
{
    public partial class Form1 : Form
    {
        private string address;
        private string response;
        private PingReply reply;
        //public string response;

        private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
        {
            if (e.Cancelled)
                ((AutoResetEvent)e.UserState).Set();
            if (e.Error != null)
                ((AutoResetEvent)e.UserState).Set();
            reply = e.Reply;
            ((AutoResetEvent)e.UserState).Set();

            if (reply == null)
                return;
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            address = IPtextbox.Text;
        }

        private void Ping_click(object sender, EventArgs e)
        {
            AutoResetEvent waiter = new AutoResetEvent(false);

            Ping pingSender = new Ping(); //creates a new 'pingSender' Ping object

            pingSender.PingCompleted += 
                new PingCompletedEventHandler(PingCompletedCallback);

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);

            int timeout = 1000;
            pingSender.SendAsync(address, timeout, buffer, waiter);
        }

        private void label1_Click(object sender, EventArgs e)
        {
            label1.Text = "the ping was: " + reply.Status.ToString();
            Show();
            Refresh();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

根据您的代码,您的标签只会在您点击时更改其文字。 label1_Click事件被提出。

PingCompleted事件,用于获取有关通过调用SendAsync方法收集的完成状态和数据的信息。在其中,您可以使用ping的结果更改标签文本。

label1_Click内的所有代码添加到PingCompletedCallback方法,如下所示;

private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
    {
        if (e.Cancelled || e.Error != null)
            ((AutoResetEvent)e.UserState).Set();

        reply = e.Reply;            

        if (reply == null)
            return;

        //Change the label here
        label1.Text = "the ping was: " + reply.Status.ToString();
        Show();
        Refresh();
    }