当用户点击我的验证按钮(在我的C#,WinForm,.net 3.5应用程序中),如果某个控件为空,我想在其周围绘制边框。例如,一个名为tbxLastName的文本框。我认为我需要像这样做 ->
ControlPaint.DrawBorder(Graphics.FromHwnd(this.Handle),
tbxLastName.ClientRectangle, Color.Firebrick, ButtonBorderStyle.Solid);
很遗憾,我不知道该将图形对象放在哪里,因为我的代码什么也没做。
我查看了所有的示例,包括这个MSDN - HERE,都在Paint事件中使用此代码。如下所示:
private void panel1_Paint(object sender, PaintEventArgs e)
{
ControlPaint.DrawBorder(e.Graphics, this.panel1.ClientRectangle,
Color.DarkBlue, ButtonBorderStyle.Solid);
}
然而,我只想在满足特定条件时让边框出现,这是由Button_Click触发的。
许多建议建议使用容器对象来保存文本框并调用它的Paint_Event。我做到了这一点,一个框出现了,但不是在控件周围。它出现在容器控件的左上角。这是我正在做的-->
private void grpImmunizationCntrl_Paint(object sender, PaintEventArgs e)
{
if (lkuNOImmunizationReason.Text.Equals(string.Empty)
{
ControlPaint.DrawBorder(
e.Graphics, lkuNOImmunizationReason.ClientRectangle,
Color.Firebrick, ButtonBorderStyle.Solid);
}
}
编辑
这是我结合这里的建议和我的经验得出的结果。
public static void HighlightRequiredFields(Control container, Graphics graphics, Boolean isVisible)
{
Rectangle rect = default(Rectangle);
foreach (Control control in container.Controls)
{
if (control.Tag is string && control.Tag.ToString() == "required")
{
rect = control.Bounds;
rect.Inflate(3, 3);
if (isVisible && control.Text.Equals(string.Empty))
{
ControlPaint.DrawBorder(graphics, rect, Color.FromArgb(173,216,230), ButtonBorderStyle.Solid);
}
else
{
ControlPaint.DrawBorder(graphics, rect, container.BackColor, ButtonBorderStyle.None);
}
}
if (control.HasChildren)
{
foreach (Control ctrl in control.Controls)
{
HighlightRequiredFields(ctrl, graphics, isVisible);
}
}
}
}
我将这个函数从任何需要的容器的Paint_Event
中调用。