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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With