0

我正在实施一个 ping 测试,以查看远程计算机是否在线。我有一个文本框,您可以在其中输入计算机 IP,然后有一个按钮,当按下该按钮时,会 ping 所有计算机以查看它们是否在线。我想更改线条的颜色以反映在线或离线(绿色或红色)。如果失败,我当前的代码会将整个文本框颜色更改为红色。

我的目标是,如果其中一台计算机未能通过 ping 测试,它会显示为红色,而其他计算机如果收到 ping 回复则保持绿色。

谢谢。

private void button_Click(object sender, EventArgs e)
{
    var sb = new StringBuilder();
    foreach (var line in txtcomputers.Lines)
    {
        string strhost = line;
        if (strhost.Length > 0)
        {
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions();
            options.DontFragment = true;
            // Create a buffer of 32 bytes of data to be transmitted.  
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 120;
            try
            {
                PingReply reply = pingSender.Send(strhost, timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                    txtcomputers.ForeColor = Color.Green;
                else
                    txtcomputers.ForeColor = Color.Red;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
4

2 回答 2

1

按照 Jon 的建议,在使用 RichTextBox 时,您需要使用SelectionStart、和来获取每行的起始字符索引。看看这是否适合你。SelectionLengthSelectionColorGetFirstCharIndexFromLine

private void button_Click(object sender, EventArgs e)
{
    var sb = new StringBuilder();
    Color originalColor = txtcomputers.SelectionColor; ;

    for (int i = 0; i < txtcomputers.Lines.Count(); i++)
    {
        var line = txtcomputers.Lines[i];
        string strhost = line;
        if (strhost.Length > 0)
        {
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions();
            options.DontFragment = true;
            // Create a buffer of 32 bytes of data to be transmitted.   
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 120;
            try
            {
                PingReply reply = pingSender.Send(strhost, timeout, buffer, options);
                txtcomputers.SelectionStart = txtcomputers.GetFirstCharIndexFromLine(i);
                txtcomputers.SelectionLength = strhost.Length;

                if (reply.Status == IPStatus.Success)
                {
                    txtcomputers.SelectionColor = Color.Green;
                }
                else
                {
                    txtcomputers.SelectionColor = Color.Red;
                }


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            txtcomputers.SelectionLength = 0;
        }
    }
    txtcomputers.SelectionColor = originalColor;
}
于 2012-08-19T02:02:44.023 回答
0

我相信 aTextBox不能有多种颜色的文本。(至少在 Windows 窗体中。您尚未指定 GUI 使用的平台。)

你应该看看RichTextBox,这绝对允许这样做

于 2012-08-18T21:18:02.107 回答