Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / Visual Basic

Default Button on a User Control

Rate me:
Please Sign up or sign in to vote.
3.57/5 (3 votes)
22 May 2009CPOL1 min read 28K   18  
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)


Written By
Team Leader mindstream solutions llc
United States United States
I am a managing director of mindstream solutions llc, Cape Coral, FL and SNS GmbH, Bayreuth, Germany. I am active in software development since 1983 and heavily focused on IBM i, formerly known as AS/400, iSeries and System i. Microsoft Development Tools are a passion, since I "grew up" with them.

Comments and Discussions

 
-- There are no messages in this forum --