Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

winforms - Change border color of Windows Forms Control on focus

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suggest to draw a rectangle around the active control as the following:

  • I need a method to get all the controls which in the form, even which they're in nested Panel or GroupBoxe.

The method:

// 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;
}
  • Then.. Drawing functionality..

The code:

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);
        };
    }
}

Good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...