Search code examples
vb.netkeyboard-shortcutskey-bindings

VB: How I Can Set a Key Shortcut for a Timer/Button


How I Can Set a Key Shortcut for a Timer/Button, Basicaly I Have two Timer Events, one Timer.Stop and Timer.Start. I Want make a keyshortcut when clicked toggle's the function (Start/Stop). Please Help, I Really need it.


Solution

  • Here's a manner to catch the Enter key. You should be able to expand on the concept to achieve what you want.

    Public Class Form1
        Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
            If e.KeyChar = Convert.ToChar(13) Then
                MsgBox("You pressed Enter")
            End If
        End Sub
    End Class
    

    Have fun!


    Here's an edit to help you with your forms:

    Let's say that you have a main form (the "outside one"), which contains one "child" window. I say "child" but it has nothing to do with inheritance, they are just forms.

    Now you want a key press to be catched by the "main" form even if the focus is on the "child" form. Here's a ninja-esque way to accomplish this. It has the quality of being simple, but it's not the most elegant. Still, it'll work as intended.

    In the "main" form, you need to keep track of the "child" form in a way which lets you use it's events, and a public Event:

    Public Class Main
        'modal variable to keep track of the child form
        Private WithEvents _childForm As Form
    
        'the rest of your main class goes here
    End Class
    

    I don't know if you have only one child Form or many, so you may consider using a List if you have more than one child Form or a variable number of them:

    Private _childFormsList As New List(Of Form)
    

    Now, every time you open a form, you have to update the modal variables in the main (I'll work on teh assumption that you have only one child Form at a time to make things easier):

    _childForm = New ChildFormClass()
    _childForm.Show()
    'or whatever you're doing with the Form
    

    Now, go back to this line from before:

    Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
    

    and add the relevant Event from the child Form:

    Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress, _childForm.KeyPressed
    

    And now this Event will trigger for both Forms. You should rename the Sub, though, as it's not only Form1 (the main Form, whatever you named it) which will trigger anymore.

    I'll hang around from time to time in case you have further questions.