在焦点上更改 Windows 窗体控件的边框颜色 [英] Change border color of Windows Forms Control on focus
本文介绍了在焦点上更改 Windows 窗体控件的边框颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 Windows 窗体(TextBox、ComboBox、MaskedTextBox,...)中的一些常见控件处于焦点时更改它们的边框颜色?我想在我的对话框中实现这一点,所以当控件处于焦点时,它的边框变成蓝色?
Is there a way to change a border color of some common controls in Windows Forms (TextBox, ComboBox, MaskedTextBox, ...) when they are in focus? I would like to achieve that in my dialog, so when control is in focus it's border becomes blue?
推荐答案
我建议在活动控件周围绘制一个矩形,如下所示:
I suggest to draw a rectangle around the active control as the following:
- 我需要一种方法来获取表单中的所有控件,即使它们位于嵌套的 Panel 或 GroupBoxe 中.
方法:
// Get all controls that exist in the form.
public static List<Control> GetAllControls(IList controls)
{
List<Control> controlsCollectorList = new List<Control>();
foreach (Control control in controls)
{
controlsCollectorList.Add(control);
List<Control> SubControls = GetAllControls(control.Controls);
controlsCollectorList.AddRange(SubControls);
}
return controlsCollectorList;
}
- 然后..绘图功能..
代码:
public Form1()
{
InitializeComponent();
// The parents that'll draw the borders for their children
HashSet<Control> parents = new HashSet<Control>();
// The controls' types that you want to apply the new border on them
var controlsThatHaveBorder = new Type[] { typeof(TextBox), typeof(ComboBox) };
foreach (Control item in GetAllControls(Controls))
{
// except the control if it's not in controlsThatHaveBorder
if (!controlsThatHaveBorder.Contains(item.GetType())) continue;
// Redraw the parent when it get or lose the focus
item.GotFocus += (s, e) => ((Control)s).Parent.Invalidate();
item.LostFocus += (s, e) => ((Control)s).Parent.Invalidate();
parents.Add(item.Parent);
}
foreach (var parent in parents)
{
parent.Paint += (sender, e) =>
{
// Don't draw anything if this is not the parent of the active control
if (ActiveControl.Parent != sender) return;
// Create the border's bounds
var bounds = ActiveControl.Bounds;
var activeCountrolBounds = new Rectangle(bounds.X - 1, bounds.Y - 1, bounds.Width + 1, bounds.Height + 1);
// Draw the border...
((Control)sender).CreateGraphics().DrawRectangle(Pens.Blue, activeCountrolBounds);
};
}
}
祝你好运!
这篇关于在焦点上更改 Windows 窗体控件的边框颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文