如何使以下异常返回BOLD和文本字体RED? “返回” WMI错误 “;”
的措辞稍后在代码中使用它来返回文本框中的WMI参数...如下所示:
private static string GetMOValue(ManagementObject mo, string name)
{
try
{
object result = mo[name];
return result == null ? "" : result.ToString();
}
catch (Exception)
{
return "***WMI Error***";
}
}
private void cmbHdd_SelectedIndexChanged(object sender, EventArgs e)
{
//try
//{
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
foreach (ManagementObject moDisk in mosDisks.Get())
{
//try
//{
txtSystemName.Text = GetMOValue(moDisk, "systemname");
txtType.Text = GetMOValue(moDisk, "MediaType");
txtModel.Text = GetMOValue(moDisk, "Model");
txtFirmware.Text = GetMOValue(moDisk, "FirmwareRevision");
.....
答案 0 :(得分:2)
TextBox不是网络浏览器。它支持使用单一字体显示文本 - 没有装饰,颜色等。您可以在运行时更改文本框的字体。
您可以处理文本框的TextChanged
事件来实现此目的,但这不是一个很好的代码示例:
private void textBox1_TextChanged(object sender, EventArgs e)
{
Font defaultFont = SystemFonts.DefaultFont;
if(textBox1.Text.StartsWith("**") && textBox1.Text.EndsWith("**"))
{
textBox1.Font = new Font(defaultFont.FontFamily, defaultFont.Size, FontStyle.Bold);
textBox1.ForeColor = Color.Red;
// note: can't change text here as it will recursively trigger this handler
}
else
{
textBox1.Font = defaultFont;
textBox1.ForeColor = SystemColors.ControlText;
}
}
更好的方法是使用一个简单的方法来设置文本和文本框属性。
肥皂盒:请注意我考虑这种形式检查**字符的文本,看它是否是一个错误,非常丑陋和不可靠。你应该做的是像
Font defaultFont = SystemFonts.DefaultFont;
try
{
textBox1.Text = GetMOValue(...);
textBox1.Font = defaultFont;
textBox1.ForeColor = SystemColors.ControlText;
}
catch(Exception ex)
{
textBox1.Text = "ERROR";
textBox1.Font = new Font(defaultFont.FontFamily, defaultFont.Size, FontStyle.Bold);
textBox1.ForeColor = Color.Red;
}
// the Font and ForeColor properties are repeatedly set in case that previous
// try had the different result (e.g. previous => error, current => OK, so
// we need to reset the attributes of textbox
您可以使用RichTextBox,WebBrowser或某些自定义绘制控件来支持更高级的格式化。
答案 1 :(得分:2)
您应该检查方法是否返回异常,如果是,则动态更改文本框的设置字体和颜色:
textBox.ForeColor = Color.Red;
textBox.Font = new Font(textBox.Font, FontStyle.Bold);
答案 2 :(得分:-1)
private void btnBold_Click(object sender, EventArgs e)
{
this.rtxText.SelectionFont = new System.Drawing.Font(rtxText.Font.FontFamily,Convert.ToInt16(nudFontSize.Value), System.Drawing.FontStyle.Bold ^ this.rtxText.SelectionFont.Style);
}
//ITALICS CODING
private void btnItalics_Click(object sender, EventArgs e)
{
this.rtxText.SelectionFont = new System.Drawing.Font(rtxText.Font.FontFamily, Convert.ToInt16(nudFontSize.Value), System.Drawing.FontStyle.Italic ^ this.rtxText.SelectionFont.Style);
}
//UNDERLINE CODING
private void btnUnderline_Click(object sender, EventArgs e)
{
this.rtxText.SelectionFont = new System.Drawing.Font(rtxText.Font.FontFamily, Convert.ToInt16(nudFontSize.Value), System.Drawing.FontStyle.Underline ^ this.rtxText.SelectionFont.Style);
}