How to detect a function key has been pressed within a text field.

© copyright 22.May.2009 by Paul Bradley filed under Visual Basic


Today I needed to extend an existing search box, by populating the text field with a default value if the user pressed the F3 function key, while the cursor was in the text box.

The best way to achieve this was by adding code to the KeyDown event, which checks that the KeyValue is equal to the key you are trying to detect. The sample code below shows how to detect the F3 function key being pressed. After defaulting the field to the correct value, I then ensure that the text box has focus, and move the cursor to the end of the value, so that the user can add additional text if necessary.

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

    If e.KeyValue = Keys.F3 Then
        ' code here to populate
        ' the default value

        txtSearch.Focus()
        SendKeys.Send("{End}")
        Exit Sub
    End If

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 has over 20 years programming experience. He also produces e-learning videos at Linux by Example

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.