How do I get a DoubleClick event in a .NET radio button?

我怕爱的太早我们不能终老 提交于 2019-12-04 03:52:19

Based on your original suggestion I made a solution without the need to subclass the radiobuton using reflection:

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;

Now the double click event for the radiobutton is fired. BTW: The suggestion of Nate using e.Clicks doesn't work. In my tests e.Clicks was always 1 no matter how fast or often I clicked the radiobutton.

You could do something like this:

myRadioButton.MouseClick += new MouseEventHandler(myRadioButton_MouseClick);

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

You may or may not also want to check that e.Button == MouseButtons.Left

Based on @MSW answer, I made this extension class:

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;
    }
}

Which is then super easy to set up and re-use:

radioButton.AllowDoubleClick((a, b) => myDoubleClickAction());

Sorry, don't have the reputation to comment on this. What action are you trying to have the double-click perform for the user? I think using a double-click may be confusing because it is different from the general mental model that a user has of a radio-button (IE single click, select one option from a set)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!