Introduction
When designing a form, the properties AcceptButton
and KeyPreview
are very useful for automating responses to user-actions like pressing the Enter-key, ESC-key etc. When you create your own user-controls, these properties are not available. At least, not right at hand.
Background
Using the Windows built-in messaging system helps us in solving this problem.
That's what we do and code
The point we have to achieve is to be informed when the user presses a key we want to react on. Say, you have designed a search dialog user control, like the file-search in Windows Explorer. When the user presses the Enter-key, the search should start. For determining the pressed key, you could use the _KeyUp
-event for each child control, which makes the code look bad and is anything but clean programming style. This is where our user-controls-KeyPreview capability comes in. To implement key-validation on user-control level, we use the .NET framework's UserControl
base class implemented function ProcessKeyPreview
. To get control of it, simply declare an override of it on the class-level.
Public Class myUserControl
Public Event onEnterKey(ByVal sender As System.Object, ByVal e As System.EventArgs)
Public Event onF4(ByVal ControlName As String)
Private Const WM_KEYDOWN = &H100
Protected Overrides Function ProcessKeyPreview(ByRef m As _
System.Windows.Forms.Message) As Boolean
If m.Msg = WM_KEYDOWN Then
Select Case m.WParam.ToInt32
Case ConsoleKey.Enter
RaiseEvent onEnterKey(button01, New System.EventArgs)
Case ConsoleKey.F4
RaiseEvent onF4(MyBase.ActiveControl.Name)
End Select
End If
Return MyBase.ProcessKeyPreview(m)
End Function
End Class
Summary
With this technique, you can offer Form-Class-style functionality to consumers of your user-control. You could even implement a property called AcceptButton
or CancelButton
to allow for more flexibility.