2009-06-30 29 views
9

我希望能夠從標準的winforms單選按鈕捕捉DoubleClick或MouseDoubleClick事件,但它們似乎隱藏起來並不起作用。目前我有這樣的代碼:如何在.NET單選按鈕中獲得DoubleClick事件?

public class RadioButtonWithDoubleClick : RadioButton 
{ 
    public RadioButtonWithDoubleClick() 
     : base() 
    { 
     this.SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true); 
    } 

    [EditorBrowsable(EditorBrowsableState.Always), Browsable(true)] 
    public new event MouseEventHandler MouseDoubleClick; 
    protected override void OnMouseDoubleClick(MouseEventArgs e) 
    { 
     MouseEventHandler temp = MouseDoubleClick; 
     if(temp != null) { 
      temp(this, e); 
     } 
    } 
} 

是否有一個更簡單和更乾淨的方法來做到這一點?

編輯:有關背景,我同意Raymond Chen的崗位here,要雙擊一個單選按鈕(如果這些是對話框上的控件)的能力,使對話只是一點點更容易使用瞭解它的人。

在Vista中使用任務對話框(請參閱this Microsoft guideline pagethis MSDN page specifically about the Task Dialog API)將是顯而易見的解決方案,但我們沒有那麼奢侈。

回答

10

根據您的原始建議I提出瞭解決方案,而不需要繼承radiobuton使用反射:

MethodInfo m = typeof(RadioButton).GetMethod("SetStyle", BindingFlags.Instance | BindingFlags.NonPublic); 
if (m != null) 
{ 
    m.Invoke(radioButton1, new object[] { ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true }); 
} 
radioButton1.MouseDoubleClick += radioButton1_MouseDoubleClick; 

現在的單選按鈕的雙擊事件。 順便說一句:Nate使用e.Clicks的建議不起作用。在我的測試中,e.Clicks總是1,無論我點擊單選按鈕的速度有多快,

3

你可以做這樣的事情:

myRadioButton.MouseClick += new MouseEventHandler(myRadioButton_MouseClick); 

void myRadioButton_MouseClick(object sender, MouseEventArgs e) 
{ 
    if (e.Clicks == 2) 
    { 
     // Do something 
    } 
} 

您可能會或可能不會還想要檢查e.Button == MouseButtons.Left

+0

我接受這一個,因爲儘管我認爲我自己的解決方案對於我的案例來說更簡單,我將多次使用相同的控件,如果有人只需要一兩個,那麼您的要簡單得多。 – Ant 2009-07-03 14:10:23

+2

由於Clicks == 2從來沒有發生過,所以這看起來似乎沒有用於.NET 3.5。 – Wernight 2011-03-08 15:09:46

0

對不起,沒有信譽評論在這。您想要爲用戶執行雙擊操作的操作是什麼?我認爲使用雙擊可能會令人困惑,因爲它與用戶具有單選按鈕(IE單擊,從一組中選擇一個選項)的一般心理模型不同。

1

基於@MSW答案,我做了這個擴展類:

static class RadioButtonEx 
{ 
    public static void AllowDoubleClick(this RadioButton rb, MouseEventHandler MouseDoubleClick) 
    { 
     // 
     // Allow double clicking of radios 
     System.Reflection.MethodInfo m = typeof(RadioButton).GetMethod("SetStyle", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); 
     if (m != null) 
      m.Invoke(rb, new object[] { ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true }); 

     rb.MouseDoubleClick += MouseDoubleClick; 
    } 
} 

,然後超級容易設置和再利用:

radioButton.AllowDoubleClick((a, b) => myDoubleClickAction()); 
相關問題