Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vb.net Keydown event on whole form

Tags:

vb.net

keydown

I have a form with several controls. I want to run a specific sub on keydown event regardless any controls event. I mean if user press Ctrl+S anywhere on form it execute a subroutine.

like image 256
Malik Avatar asked Dec 05 '12 15:12

Malik


People also ask

How use Keydown event in VB NET?

Select your VB.Net source code view in Visual Studio and select TextBox1 from the top-left Combobox and select KeyDown from top-right combobox , then you will get keydown event sub-routine in your source code editor.

What is the difference between the Keydown and KeyUp events?

In this article Occur in sequence when a user presses and releases a key. KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.

Is Keydown an event?

The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

What is the return value of Keydown function?

So, Using keydown() method we can detect if any key is on its way down. Here selector is the selected element. Parameter: It accepts an optional parameter as a function which gives the idea whether any key is pressed or not. Return values: It returns whether any key is pressed or not or which key is pressed.


1 Answers

You should set the KeyPreview property on the form to True and handle the keydown event there

When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus. .......... To handle keyboard events only at the form level and not allow controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event handler to true.

So, for example, to handle the Control+S key combination you could write this event handler for the form KeyDown event.

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles MyBase.KeyDown
    If  e.Control AndAlso e.KeyCode = Keys.S then
        ' Call your sub method here  .....
        YourSubToCall()

        ' then prevent the key to reach the current control
        e.Handled = False 
    End If
End Sub
like image 137
Steve Avatar answered Sep 28 '22 01:09

Steve