Page 1 of 1

How to detect keyboard press and toggle events

Posted: Mon Dec 08, 2008 11:09 am
by Mistrel
I've seen a lot of variations of this on the forum so I whipped up this example to demonstrate how the significant bits of the GetKeyState_() result actually work.

Code: Select all

OpenWindow(0,0,0,160,120,"")
TextGadget(0,8,8,80,20,"")
TextGadget(1,8,32,80,20,"")
TextGadget(2,8,48,80,20,"")
Repeat
	KeyState.w=GetKeyState_(#VK_SHIFT)
	SetGadgetText(0,"Binary "+LSet(Right(Bin(KeyState),8),8,"0"))
	If KeyState&%10000000
		KeyPressed=1
	Else
		KeyPressed=0
	EndIf
	SetGadgetText(1,"KeyState "+Str(KeyPressed))	
	If KeyState&%00000001
		ToggleState=1
	Else
		ToggleState=0
	EndIf
	SetGadgetText(2,"ToggleState "+Str(ToggleState))
Until WaitWindowEvent(100)=#WM_CLOSE
End
For more information on GetKeyState vs GetAsyncKeyState see here:
http://blogs.msdn.com/oldnewthing/archi ... 72262.aspx

Here is an example for detecting mouse events and returning their result in a bitmask:

Code: Select all

Procedure MouseClick()
	If GetKeyState_(#VK_LBUTTON)&%10000000
		LButton=1
	EndIf
	If GetKeyState_(#VK_MBUTTON)&%10000000
		MButton=2
	EndIf
	If GetKeyState_(#VK_RBUTTON)&%10000000
		RButton=4
	EndIf
	If GetKeyState_($05)&%10000000
		XButton1=8
	EndIf
	If GetKeyState_($06)&%10000000
		XButton2=16
	EndIf
	ProcedureReturn (LButton|MButton|RButton|XButton1|XButton2)
EndProcedure

Posted: Mon Dec 08, 2008 11:04 pm
by SFSxOI
Thanks Mistrel.

I haven't tried it yet, but is something missing from the example code?

EDIT: Got it, this is missing I think

Code: Select all

CreateGadgetList(WindowID(0))

Posted: Mon Dec 08, 2008 11:09 pm
by Mistrel
That line is only required for 4.20 and below. Sorry it didn't compile for you the first time. :)

Posted: Mon Dec 08, 2008 11:27 pm
by SFSxOI
no problem, im using 4.20 and didn't think about it being that way for 4.3. I appreciate it though, gonna use it in something. :)

Posted: Sun Jan 04, 2009 3:13 pm
by Blue
Hey, thanks Mistrel,
Now I finally know how to detect the bak and forward buttons on my fancy mouse.

Do you know how to go about detecting in advance the number of buttons present on a mouse?

Posted: Mon Jan 05, 2009 1:10 am
by LCD
I want to join to the thanks-thread... It helped me to fix a bug in Retro-X, where unwanted pixels are painted. I know now also too, how to use additional buttons on my mouse.