Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Default Button on a User Control

3.57/5 (3 votes)
22 May 2009CPOL1 min read 28.2K  
How to make a default button or emulate an AcceptButton on a User Control.

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.

VB
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)