简体   繁体   中英

Click Button Pressing Spacebar in VB.Net

I had 2 goals:

  • Make pressing enter over a textbox start a search function
  • Make pressing spacebar over a button perform a click(thought it was its behaviour, seems not)

I reached the first goal programmatically clicking the button of the seach, executing then the search function:

Private Sub txtSearch_KeyDown(sender As Object, e As KeyEventArgs) Handles txtSearch.KeyDown
    If e.KeyValue = Keys.Enter Then
        btnSearch.PerformClick()
    End If
End Sub

It worked, so I tried the same method with my second goal:

Private Sub btnCancel_KeyDown(sender As Object, e As KeyEventArgs) Handles btnCancel.KeyDown
    If e.KeyValue = Keys.Space Then
        btnCancel.PerformClick()
    End If
End Sub

And this actually does nothing, kinda select the button, but it doesn't process the button_click event.
Did I miss something?

Try this.

Dim btn As New MouseButtons   'create a new instance of mousebutton
Dim a As New MouseEventArgs(btn, 1, 1, 1, 1) 'simulate a click

If e.KeyValue = Keys.Space Then
  Button1_MouseClick(sender, a)
End If

你必须在 Btncancel.Keydown() 或 Btncancel.KeyPress() 事件之前调用 BtnCancel.Focus()

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