我正在尝试创建一个简单的ping程序GUI实现。我有一个表单,它只是一个文本框textBox1
,用户输入IP作为字符串,按下按钮Ping
,ping的结果显示在标签label1
中。出于某种原因,运行程序时文本不会显示。从Ping.SEndAsync部分采取在标签文本中显示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();
}
}
}
没有文字上的MSDN(而不是只使用一半),并通过有关SendAsync像http://stackoverflow.com/questions一些其他的问题,阅读ping_click' –
仔细阅读整个样本'设置部分标签/ 9748245/how-to-use-ping-sendasync-working-with-datagridview会有所帮助。 –