How do I clear the keyboard buffer?

D

Don

I've got a loop from within which I make a call to the API function
GetAsyncKeystate to see if the Escape key was pressed. If it is, then the
exit condition of the loop is met and the program goes on to display a
simple messagebox. Unfortunately, the program seems to think the Escape key
was meant for this messagebox, even though it appeared *after* the Escape
key was pressed(!) and instantly closes the messagebox before you can even
see it. Thru testing, I have become 100% positive that hitting the Escape
key to exit the loop is causing the problem.

I've tried two methods of clearing the keyboard buffer that I've found (both
were for VB5/6). On involved using the SetKeyboardState API call and the
other involved PeekMessage. Neither worked. I even tried making a loop
where GetAsyncKeystate was called repeatedly (i.e. Do: Loop Until
(GetAsyncKeyState(Keys.Escape) And &H8000) = 0)until it thought the Escape
key was no longer pressed...and the message box still didn't appear!

If I tested for another key, like the 'E' key, it worked fine and the
messagebox appeared (it didn't receive any Escape character to close
itself).

I can't figure out how to get around this. Is there anything I can do to
absorb the Escape key if it's there and do nothing if it's not? Is there
anyway to clear the real keyboard buffer that must exist somewhere that
GetAsyncKeystate doesn't have access to?

This is essentially what the code looks like (extraneous stuff removed):


Do
' Do whatever; hit Escape in here to exit loop
Loop until (GetAsyncKeyState(Keys.Escape) And &H8000) <> 0

Msgbox "Hello!" ' <--- Will not appear if we tested for Keys.Escape
' in call to GetAsyncKeyState above.
Msgbox "Goodbye!" ' <--- Will appear always.


Does anyone have any insight?

- Don
 
F

Fergus Cooney

Hi Don,

Putting Application.DoEvents after your loop will cause messages on the
message queue to be used up. This will include your Escape Key which will go
to the currently active control. If your Form has a button set as the Cancel
button (ie, in response to Escape), this will be triggerred, oops. If not,
however, the key will be discarded

Another possible solution is to call Application.DoEvents <within> your
loop which would allow the user to click a [Stop] button. This could then set
a variable which your loop checks.

Another way is to do this with threads, but that may be getting a bit
heavy for what your app is doing.

Regards,
Fergus
 
D

Don

Fergus Cooney said:
Hi Don,

Putting Application.DoEvents after your loop will cause messages on the
message queue to be used up.

And here I thought they got rid of good ol' DoEvents. Thanks! It worked!

- Don
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top