Search code examples
vb.netkeypresskeydown

(VB) How to detect a keypress only once, even when holding the key down?


I have been working on a large game project lately and have been though a couple methods for detecting keyboard input. For movement I use getasynckeystate (which is perfect) because it sends a signal every tick that the key is being pressed.

Then comes the other method, which is keydown. This method works with single keypresses, but then a second later starts spamming the keypress action.

My goal is to find something that will only detect your keypress once, even if you hold down the key; once you let go of the key it will let you hit it again. Please help and thanks for reading this!

Examples:

if GetAsyncKeyState(Convert.ToInt32(Keys.W)) then.... if e.keycode = keys.B then....


Solution

  • The 'keyUp' event captures the key that was pressed or which remained pressed only once:

    Sub Control_KeyUp(sender As Object, e As KeyEventArgs) Handles Control.KeyUp
            MsgBox("Pressed key: " & e.KeyCode.ToString())
    End Sub
    

    Edit: Removed Private access so it can be called from another class.