[英]textbox only allow ip address in textbox c#
我正在尝试使文本框仅允许IP地址而不使用Internet进行验证。 我将有一个“ private void textBox3_TextChanged”或一个“ timer1_Tick”来完成这项工作。 并且每次输入或打勾时,它都会检查它是否有效。 这就是为什么我希望它速度快,并且仅使用简单的本地代码来检查它是否有效,这意味着0.0.0.0-255.255.255.255。
首先,它不应执行任何操作,但是在写入ip后,它将启动计时器,然后检查该ip是否可访问。 这样做的目的是,当IP写入后,如果ip大约4秒后仍无法访问ip,则图片框将变为红色;如果可达,则它将变为绿色,然后停止直到“ textbox3_TextChanged”
我尝试了类似ping的操作,但如果未键入任何内容,则崩溃;如果无法访问ip,它会滞后:
private void timer1_Tick(object sender, EventArgs e)
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = false;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "ping";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply = pingSender.Send(textBox3.Text, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
pictureBox4.BackColor = Color.LimeGreen;
}
else
pictureBox4.BackColor = Color.Red;
}
这是屏幕截图: http : //imgur.com/Cvix2Tr
请帮忙 :)
您可以尝试将textbox3_TextChanged
替换为以下内容:
(对于本示例,我的界面有一个名为textBox
TextBox和一个名为textBlock
TextBlock)
//async to not freeze the UI
private async void TextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{
Ping pingSender = new Ping();
var tb = (TextBox)sender;
//a little regex to check if the texbox contains a valid ip adress (ipv4 only).
//This way you limit the number of useless calls to ping.
Regex rgx = new Regex(@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$");
if (rgx.IsMatch(tb.Text))
{
int timeout = 120;
try
{
var reply = await pingSender.SendPingAsync(tb.Text, timeout);
textBlock.Text = reply.Status == IPStatus.Success ? "OK" : "KO";
}
catch (Exception ex) when (ex is TimeoutException || ex is PingException)
{
textBlock.Text = "KO";
}
}
else
{
if (textBlock != null)
{
textBlock.Text = "Not valid ip";
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.