Изменить цвет границы элемента управления Windows Forms на фокусе - PullRequest
0 голосов
/ 29 октября 2010

Есть ли способ изменить цвет границы некоторых общих элементов управления в Windows Forms (TextBox, ComboBox, MaskedTextBox, ...), когда они находятся в фокусе? Я хотел бы добиться этого в своем диалоговом окне, поэтому, когда элемент управления находится в фокусе, его рамка становится синей?

1 Ответ

0 голосов
/ 29 октября 2010

Я предлагаю нарисовать прямоугольник вокруг активного элемента управления следующим образом:

  • Мне нужен метод, чтобы получить все элементы управления в форме, даже если они находятся во вложенной панели или 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);
        };
    }
}

Удачи!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...