2015-04-01 79 views
1

我想在任何具有焦点的控件上绘制边框,当控件不再具有焦点时,边框必须消失。我曾尝试在下面的代码中绘制边框,但我不知道如何在边框消失之前将其绘制。当控件聚焦时绘制边框

void mButton_Paint(object sender, PaintEventArgs e) { 
    ControlPaint.DrawBorder(e.Graphics, ((Control)sender).ClientRectangle, Color.DarkBlue, ButtonBorderStyle.Solid); 
} 
+0

你想把边界放在控件内还是外边?容器内是否有任何控件?有些控件甚至没有关注。你的问题太模糊了。更加详细一些。 – 2015-04-01 03:14:45

+0

用'if((Control)sender == ActiveControl)给paint代码添加前缀。“Paint由系统触发,至少对于按钮和其他控件来说,无论如何都会改变焦点。对于其他人,您需要观看离开/进入事件。 – TaW 2015-04-01 06:01:44

+0

我编辑了我的答案,小小的优化。 – RenniePet 2015-04-01 14:06:06

回答

1

试试这个。 (原来比我预想的要混乱得多。)

public partial class FormSO29381768 : Form 
    { 
     // Constructor 
     public FormSO29381768() 
     { 
     InitializeComponent(); 

     InstallEventHandlers(this); 
     } 


     /// <summary> 
     /// Recursive method to install the paint event handler for all container controls on a form, 
     /// including the form itself, and also to install the "enter" event handler for all controls 
     /// on a form. 
     /// </summary> 
     private void InstallEventHandlers(Control containerControl) 
     { 
     containerControl.Paint -= Control_Paint; // Defensive programming 
     containerControl.Paint += Control_Paint; 

     foreach (Control nestedControl in containerControl.Controls) 
     { 
      nestedControl.Enter -= Control_ReceivedFocus; // Defensive programming 
      nestedControl.Enter += Control_ReceivedFocus; 

      if (nestedControl is ScrollableControl) 
       InstallEventHandlers(nestedControl); 
     } 
     } 


     /// <summary> 
     /// Event handler method that gets called when a control receives focus. This just indicates 
     /// that the whole form needs to be redrawn. (This is a bit inefficient, but will presumably 
     /// only be noticeable if there are many, many controls on the form.) 
     /// </summary> 
     private void Control_ReceivedFocus(object sender, EventArgs e) 
     { 
     this.Refresh(); 
     } 


     /// <summary> 
     /// Event handler method to draw a dark blue rectangle around a control if it has focus, and 
     /// if it is in the container control that is invoking this method. 
     /// </summary> 
     private void Control_Paint(object sender, PaintEventArgs e) 
     { 
     Control activeControl = this.ActiveControl; 
     if (activeControl != null && activeControl.Parent == sender) 
     { 
      e.Graphics.DrawRectangle(Pens.DarkBlue, 
         new Rectangle(activeControl.Location.X - 2, activeControl.Location.Y - 2, 
             activeControl.Size.Width + 4, activeControl.Size.Height + 4)); 
     } 
     } 
    } 
+0

谢谢!我会尝试! – Andy 2015-04-01 11:32:22