2011-12-02 18 views
1

我有一個從父窗體加載的子窗體。父窗體不是MDI父窗體。 我想要做到以下幾點:C#窗體控件樣式,通過樣式變化移除焦點

我想禁用具有焦點的控件,特別是按鈕和RadioButtons的虛線/虛線矩形。

目前我使用下面的代碼:

foreach (System.Windows.Forms.Control control in this.Controls) 
{ 
    // Prevent button(s) and RadioButtons getting focus 
    if (control is Button | control is RadioButton) 
    { 
     HelperFunctions.SetStyle(control, ControlStyles.Selectable, false); 
    } 
} 

哪裏我的SetStyle方法是

public static void SetStyle(System.Windows.Forms.Control control, ControlStyles styles, 
    bool newValue) 
{ 
    // .. set control styles for the form 
    object[] args = { styles, newValue }; 

    typeof(System.Windows.Forms.Control).InvokeMember("SetStyle", 
     BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, 
     null, control, args); 
} 

不用說,這似乎並沒有工作。我不知道我在這裏失去了什麼。任何建議和/或建議將不勝感激。

回答

2

嗯,我想我已經找到了某種解決方案。該解決方案解決了焦點矩形問題,但沒有回答原始代碼發佈錯誤的問題。這是我對矩形問題的理解....請隨時糾正我,如果我有任何這個錯誤。

看起來有兩種類型的虛線/虛線矩形:指示控件被聚焦的矩形,以及指示控件是默認控件的矩形。這兩種情況都需要你爲控件創建一個自定義類。在我的情況下,感興趣的控件是一個RadioButton。因此,這裏是代碼:

public class NoFocusRadioButton: RadioButton 
{ 
    // ---> If you DO NOT want to allow focus to the control, and want to get rid of 
    // the default focus rectangle around the control, use the following ... 

    // ... constructor 
    public NoFocusRadioButton() 
    { 
     // ... removes the focus rectangle surrounding active/focused radio buttons 
     this.SetStyle(ControlStyles.Selectable, false); 
    } 
} 

或使用以下命令:

public class NoFocusRadioButton: RadioButton 
{ 
    // ---> If you DO want to allow focus to the control, and want to get rid of the 
    // default focus rectangle around the control, use the following ... 

    protected override bool ShowFocusCues 
    { 
     get 
     { 
      return false; 
     } 
    } 
} 

我使用的第一個(構造函數代碼)的方式,不允許輸入焦點。

這一切都很好解決矩形問題,但我仍然不明白爲什麼最初的代碼不起作用。