Now to the core of this article; Implementing Mnemonics in Custom Controls.
First we need to Implement an Interface. So in your button class code, right after the Inherits System.Windows.Forms.UserControl, add
| Implements IButtonControl|
There are now three(3) subsequent Subs / Functions we need to implement and one(1) Property.
If you’re like me, you try to keep the properties with the properties, the subs with the subs, etc.. In a class, however you can add these anywhere in the class.
First let's implement the NotifyDefault Sub. Nothing will actually happen here, but we have to add it to satisfy the "Implements IButtonControl"
| Public Sub NotifyDefault() Implements IButtonControl.NotifyDefault
‘Nothing Happens Here
Next we’ll implement the DialogResult property. The DialogResult property is like the dialog result property for any type of form, button, messagebox, open file dialog…anything. It simply supplies the UI with a corresponding result for certain actions.
|Private m_DialogResult as DialogResult
Public Property DialogResult() as DialogResult Implements IButtonContro.DialogResult
Set (ByVal value as DialogResult)
If [Enum].IsDefined(GetType(DialogResult), value) Then
m_DialogResult = value
We now need to Implement the PerformClick method. This is what allows the Mnemonic call to perform any actions associated with the OnClick method and the subsequent Click Event.
| Public Sub PerformClick() Implements IButtonControl.PerformClick
And last but not least, the Function that does it all:- ProcessMnemonic. This is the function that determines which key combinations are being pressed while the UI the control is on is active. .NET has a couple of built in functions that help us determine two things.
- Is the key that’s being pressed the Key that we want to process and therefore perform our actions.
- Is there a control key that’s being held. Control keys are keys like Alt, Ctrl, Return, etc.
| Public Overrides Function ProcessMnemonic(ByVal c as Char) as Boolean
If (Control.IsMnemonic(c, Me.Text) and (Control.ModifierKeys = Keys.Alt)) Then
And that’s it. You should now be able to recompile your control. Add it to a form, run the form and press “Alt + ‘YourMnemonicKey’”. Barring you have something in the Click event of the control, that event should fire.