Using Function Keys to Activate Command Buttons in Visual Basic 2005.

© copyright 09.Oct.2009 by Paul Bradley filed under Visual Basic


[Ad] need a break from coding?

Hoseasons Villas

I have been programming with Visual Basic for over 7 years, and have never needed to add function key actions to command buttons until this week. All the applications I have developed in the past have been mouse orientated, and have not required keyboard shortcuts for all the major functions.

However this new application I am developing is going to be used by power users, who require consistent keyboard shortcuts across all data entry screens, so I had to come up with keyboard function key shortcuts for the applications major functions.

After using the DOS database engine DataEase for many years, I decided to borrow their function key mappings which where F2 to insert a new record, F7 to delete an existing record and F8 to update the current record. Below are the steps I took to achieve this, each form has three command buttons to perform each of these tasks.

Step 1 - Add function key text to the command button

command button text

Firstly you need to add some text to each of the command buttons, to give your users visual feedback as to the shortcut being used for that button. I prefer to put these keyboard mappings in square brackets.

Step 2 - Turn on the KeyPreview property of the form

setting keypreview property

Next you need to go to the properties window for the form, and find the KeyPreview property and change it True. This will allow you to monitor each key being pressed while the form is active, filtering your desired function key shortcuts for special attention.

Step 3 - Add the following code to the forms KeyDown event

Private Sub frmDemographics_KeyDown(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown

    Select Case e.KeyCode
        Case Keys.F2
            cmdInsert.PerformClick()

        Case Keys.F7
            cmdDelete.PerformClick()

        Case Keys.F8
            cmdUpdate.PerformClick()
    End Select

End Sub

 


If you have found this article helpful or useful please consider linking to it, emailing it to friends, or share it with others using social sites like del.icio.us, Stumble Upon or Twitter.

Paul Bradley

About the Author
Paul Bradley is a VB.NET software developer living and working in Cumbria. He provides PHP & MySQL bespoke development services via his software development company, Carlisle Software Limited.
He has over 20 years programming experience.

Other Popular Articles

Categories & Topics

Home · Apache · JavaScript · Perl · PDF · PHP · MySQL · MSSQL · TAR · Ubuntu Linux · Video · Visual Basic

Browse the complete article history, and if you like what you see; consider subscribing to the rss feed.