【发布时间】:2015-12-17 03:57:25
【问题描述】:
我正在尝试创建 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();
}
}
}
【问题讨论】:
-
ping_click标签中没有文字设置部分 -
仔细阅读 MSDN 上的整个示例(而不是只使用一半)并阅读有关 SendAsync 的其他一些问题(例如 stackoverflow.com/questions/9748245/…)会有所帮助。