Search code examples
vb6crashkeypresscrash-dumps

VB6 app crashes when key is held down


I have a VB6 application with a form that processes input via its KeyPress event. In that method, it checks to see what ASCII code has been passed in via a series of if statements, and runs the necessary code to respond to the input. So, the basic format is:

Private Sub Form_Keypress (KeyAscii As Integer)

If KeyAscii = 97
' Do some stuff

If KeyAscii = 98
' Do some different stuff

End Sub

There are 24 keys connected to a keyboard encoder that provide input from buttons on the front of the kiosk. The OS is Windows 7. The problem that I have is if I hold one of these keys down for about ten seconds, the app simply crashes -- no exception, just stops executing. I did collect a few mini-dumps, and I don't see anything that gives me any usable information, but I am not experienced in reading them.

I need to know why the app can't seem to handle a stream of key presses and how to get around it.


Solution

  • I'd re-code it to look more like this:

    Private Sub Form_Keypress (KeyAscii As Integer)
        Static bInKeyPress As Boolean
        If bInKeyPress = True Then Exit Sub
    
        On Error GoTo Handler
    
        bInKeyPress = True
    
        If KeyAscii = 97
            ' Do some stuff
    
        ElseIf KeyAscii = 98
            ' Do some different stuff
    
    ' Everything goes through here, after execution is complete.
    ' Handler also calls through to this, to make sure we clean up things
    ExitPoint:
        bInKeyPress = False
        Exit Sub
    
    'Do any error handling / logging you want, here, then clean things up.
    Handler:
        GoTo ExitPoint
    End Sub
    

    Use a Static variable inside the Sub itself if you don't want anything else to be able to reset the variable, and it'll only toggle back to False when your processing finishes. Use a Private variable at the module level if you think something else should be able to control whether the Keypress function needs to be enabled or not.

    Basically, you're wanting to stop listening to key presses whilst processing anything.


    EDIT: Cleaned this up to align with some of the suggestions in the comments, and to clarify the program flow.