简体   繁体   中英

Focus on KeyDown in VB.NET?

I have seen similar questions which attempt to solve this issue, but none seem to work for me so far...

Basically, for my first VB project, I am creating a virtual keyboard where a sound is played from the resources on KeyDown. So far, the program seems to work except for the fact that each key needs to be clicked by the mouse before the sound is played by pressing each key (hence put the object in focus), where I need the key to play the sound without clicking the keyboard key (put the object in focus on KeyDown). Below is an example of my code:

Private Sub C_KeyDown(ByVal sender As System.Object, ByVal e As PreviewKeyDownEventArgs) Handles C.PreviewKeyDown ' C is the label attached to the first 'Rectangle' (Key)
    If (e.KeyCode = Keys.A) Then 'The A key should activate the C key on the keyboard 
        My.Computer.Audio.Play(My.Resources.C, _
                                   AudioPlayMode.Background)
    End If
End Sub

I have KeyPreview set to 'True' under the form's properties.

Thanks

First you must set the form property KeyPreview to true . Then you can use the from event KeyDown instead of the event of individual buttons

Private Sub MyForm_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
    Select Case e.KeyCode
        Case Keys.A
            Console.Beep(440, 200)
        Case Keys.B
            Console.Beep(494, 200)
        Case Keys.C
            Console.Beep(523, 200)
    End Select
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