C#在焦点丢失后在背景上运行Ping;将值返回到TextBox触发的焦点丢失

时间:2014-11-14 16:07:09

标签: c#

所以我有一个文本框,我输入需要ping的PC的名称。我在焦点丢失时运行ping:

private void Name_LostFocus(object sender, System.EventArgs e)
{
     if (PCIsOnline(textBox.Text))
     {
          textBox.Background = Brushes.LightGreen;
     }
     else
     {
          textBox.Background = Brushes.LightSalmon;
     }
}

PCIsOnline看起来像这样:

public static bool PCIsOnline(string arg)
{
     Ping pingSender = new Ping();
     PingOptions options = new PingOptions();
     options.DontFragment = true;
     string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
     byte[] buffer = Encoding.ASCII.GetBytes(data);
     int timeout = 40;
     try
     {
          PingReply reply = pingSender.Send(arg, timeout, 
                                            buffer, options);
          if (reply.Status == IPStatus.Success) 
               return true;
          else 
               return false;
     }
     catch
     {
          return false;
     }
}

当PC在线时,一切都很好,我没有冻结,但当PC离线时,我的应用程序会冻结一段时间。这是正常的我知道,ping离线PC需要时间。但我的问题是:如何在后台启动ping,当它结束时,这将改变启动ping的文本框的背景颜色,具体取决于ping的结果。

我已经阅读了一些关于此问题的主题,运行ping async,但这对我的情况没有帮助,至少我无法在我的代码中实现它。

1 个答案:

答案 0 :(得分:0)

您应该在单独的线程中调用PCIsOnline(textBox.Text)函数。也许这可以帮助: how to call the method in thread with aruguments and return some value 祝你好运!