how to check if any key was pressed

BlitzMax Forums/BlitzMax Beginners Area/how to check if any key was pressed

anawiki(Posted 2005) [#1]
Hi
How to check if any key was pressed without holding the program, like waitkey does. I can you keyhit, but I have to specify the keycode. Is there a command that will return true if any key was pressed?


Perturbatio(Posted 2005) [#2]
Graphics 640,480,0,0

Local k:Int

While Not KeyDown(KEY_ESCAPE)
	Cls
	
	k = GetKey()
	If k Then Print k
	
	Flip
Wend
End


Function GetKey:Int()
	Const RepeatRate : Int = 100 'ms
	Global LastTime:Long = MilliSecs()
	Global LastKey:Int = 0
	Local key:Int = 0
		
	While  Key <= 226
		If KeyDown(key) Then Exit
		Key:+ 1
	Wend
	
	
	
	If Key = 227 Then Return 0
	
	If Key = LastKey Then
		If MilliSecs()-LastTime < RepeatRate Then Return 0
	EndIf
	
	LastTime = MilliSecs()
	LastKey = Key
	If Key < 227 Then Return Key Else Return 0
	
End Function



JazzieB(Posted 2005) [#3]
You don't even have to do that. Just use GetChar() in your loop, as it doesn't wait like WaitKey does. If it returns anything other than 0, a key has been pressed. It returns ASCII codes, not key codes, though just something to be aware of if you need to use it.


Perturbatio(Posted 2005) [#4]
oops, forgot about that. The function I posted was taken from my console thingy and as you can see takes into account repeat rate. If you don't care about that, then yes, use getChar()


JazzieB(Posted 2005) [#5]
GetChar() uses your current system key repeat rates as well ;)


Perturbatio(Posted 2005) [#6]
hmmm... maybe it was because GetChar() doesn't support shift and control etc...


JazzieB(Posted 2005) [#7]
True, but if a player is asked to press any key, which ones do you think they tend to hit? Space and Enter are the only two that tend to get pressed, and if they have the hands over the keyboard at the time it's highly unlikely they'll be hovering over Shift or Ctrl.

It basically boils down to whether you want to check EVERY key or the majority of them, knowing that it's pretty much covered. Either way, then both solutions have just been posted.


Perturbatio(Posted 2005) [#8]
True, but if a player is asked to press any key, which ones do you think they tend to hit?


Yes, but as I said, I created it for a different purpose (console).


anawiki(Posted 2005) [#9]
Thanks for solution guys. I'll stick with GetChar, although Perturbatio solution is very interesting example.

It's funny that we've got almost finished game and I ask such a lame questions :)