简体   繁体   中英

How I Can Create a Keyboard shortcut to a Button?

I Want use a Keyboard key, to create a Keyboard shortcut to the Button1:

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Toggle = Toggle + 1
    If Toggle = 1 Then
        Timer1.Start()
        Button1.Text = "Toggle Off"
    Else
        Timer1.Stop()
        Toggle = 0
        Button1.Text = "Toggle On"
    End If

Timer1 Function:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Randomize()
    Dim rnd As New Random
    Dim minval As Integer
    Dim maxval As Integer

    minval = 1000 / TrackBar1.Value
    maxval = 1000 / TrackBar2.Value

    Timer1.Interval = rnd.Next(maxval, minval)

    If MouseButtons = MouseButtons.Left Then
        mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
        mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    End If
End Sub

I didn't read the whole thread, but I think, you will find some more information here.

Basically you need to do these steps:

  1. Catch System or Application Level Keydown Event
  2. Check what key was pressed
  3. If the key that should be used as shortcut was pressed, call the Click Handling Sub of your Button

So as example with Form Keydown Event, Calling the Button "LeButton" with the Shortcut "a" (When Key 'a' is pressed) (This example doesn't work, because MyBase.KeyDown isn't an application-wide Event but it may help you)

Public Sub form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown   
   If e.KeyCode = Keys.A Then
      LeButton_Click()
   End If
End Sub

Public Sub LeButton_Click(sender As Object, e As EventArgs) Handles LeButton.Click
     MsgBox("This is a Message Box")
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM