Creating a Windows Forms RadioButton that supports the double click event
Another of the peculiarities of Windows Forms is that the
RadioButton
control doesn't support double clicking. Granted,
it is not often you require the functionality but it's a little
odd it's not supported.
As an example, one of our earlier products which never made it
to production uses a popup dialog to select a zoom level for a
RichTexBox
. Common zoom levels are provided via a list of
radio buttons. Rather than the user having to first click a zoom
level and then click the OK button, we wanted the user to be
able to simply double click an option to have it selected and
the dialog close.
However, once again with a simple bit of overriding magic we can enable this functionality.
Create a new component and paste in the code below (using
and
namespace
statements omitted for clarity).
public partial class RadioButton : System.Windows.Forms.RadioButton
{
public RadioButton()
{
InitializeComponent();
this.SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true);
}
[EditorBrowsable(EditorBrowsableState.Always), Browsable(true)]
public new event MouseEventHandler MouseDoubleClick;
protected override void OnMouseDoubleClick(MouseEventArgs e)
{
base.OnMouseDoubleClick(e);
// raise the event
if (this.MouseDoubleClick != null)
this.MouseDoubleClick(this, e);
}
}
This new component inherits from the standard RadioButton
control and unlocks the functionality we need.
The first thing we do in the constructor is to modify the
components control styles to enable the StandardDoubleClick
style. At the same time we also set the StandardClick
style as
the MSDN documentation states that StandardDoubleClick
will be
ignored if StandardClick
is not set.
As you can't override an event, we declare a new version of the
MouseDoubleClick
event using the new
keyword. To this new
definition we add the EditorBrowsable
and Browsable
attributes so that the event appears in the IDE property
inspectors and intellisense.
Finally, we override the OnMouseDoubleClick
method and invoke
the MouseDoubleClick
event whenever this method is called.
And there we have it. Three short steps and we now have a radio button that you can double click.
Update History
- 2010-06-25 - First published
- 2020-11-21 - Updated formatting
Leave a Comment
While we appreciate comments from our users, please follow our posting guidelines. Have you tried the Cyotek Forums for support from Cyotek and the community?