[英]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.