我正在实施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);
}
}
}
}
答案 0 :(得分:1)
在Jon建议使用RichTextBox时,您需要使用SelectionStart
,SelectionLength
,SelectionColor
和GetFirstCharIndexFromLine
来获取每行的起始字符索引。看看这是否适合你。
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;
}
答案 1 :(得分:0)
我认为TextBox
不能有多种颜色的文字。 (至少在Windows窗体中。您尚未指定GUI正在使用的平台。)
你应该看看RichTextBox
,而确实允许这样做。