2015-04-01 119 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