2010-10-28 79 views
0

当Windows窗体(TextBox,ComboBox,MaskedTextBox,...)中的某些常用控件焦点对齐时,是否有方法更改它们的边框颜色?我想在我的对话框中实现这一点,所以当控制焦点时,它的边界变成了蓝色?在焦点上更改Windows窗体控件的边框颜色

回答

0

我建议提请各地的主动控制,如下一个矩形:

  • 我需要一个方法来获得所有的控制,其形式,即使他们嵌套的面板或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); 
     }; 
    } 
} 

祝你好运!