我正在实现一个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);
}
}
}
}发布于 2012-08-19 10:02:44
在使用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;
}发布于 2012-08-19 05:18:02
我相信TextBox中不能有多种颜色的文本。(至少在Windows窗体中。您尚未指定GUI正在使用的平台。)
您应该改为使用RichTextBox,这确实可以做到这一点。
https://stackoverflow.com/questions/12022326
复制相似问题