EventHandler to detect key presses and mouse clicks
Posted: Sun May 01, 2011 6:09 pm
A member of the German PureBasic forum wrote me a PM and asked me
for an example to detect key presses in an activated window much like
GetAsyncKeyState in Windows. I therefore extended one of my previous
examples that detects a left, right and middle button mouse click, to
also detect a key press and display the pressed key or clicked button:
for an example to detect key presses in an activated window much like
GetAsyncKeyState in Windows. I therefore extended one of my previous
examples that detects a left, right and middle button mouse click, to
also detect a key press and display the pressed key or clicked button:
Code: Select all
EnableExplicit
ImportC ""
GetEventClass(Event)
EndImport
#kEventClassMouse = 'mous'
#kEventClassKeyboard = 'keyb'
#kEventMouseButtonPrimary = 1
#kEventMouseButtonSecondary = 2
#kEventMouseButtonTertiary = 3
#kEventMouseDown = 1
#kEventParamKeyMacCharCodes = 'kchr'
#kEventParamKeyModifiers = 'kmod'
#kEventParamMouseButton = 'mbtn'
#kEventRawKeyDown = 1
#typeChar = 'TEXT'
#typeMouseButton = 'mbtn'
#typeUInt32 = 'magn'
Structure EventTypeSpec
EventClass.L
EventKind.L
EndStructure
Define EventHandlerUPP.L
Procedure EventHandler(*NextEventHandler, Event.L, UserData.L)
Protected ButtonType.L
Protected KeyCode.L
Protected KeyModifier.L
Select GetEventClass(Event)
Case #kEventClassMouse
If GetEventParameter_(Event, #kEventParamMouseButton, #typeMouseButton, 0, 4, 0, @ButtonType) = 0
If GetEventParameter_(Event, #kEventParamKeyModifiers, #typeUInt32, 0, 4, 0, @KeyModifier) = 0
Select ButtonType
Case #kEventMouseButtonPrimary
If KeyModifier = $00001000
SetGadgetText(1, "Right mouse button")
Else
SetGadgetText(1, "Left mouse button")
EndIf
Case #kEventMouseButtonSecondary
SetGadgetText(1, "Right mouse button")
Case #kEventMouseButtonTertiary
SetGadgetText(1, "Middle mouse button")
EndSelect
EndIf
EndIf
Case #kEventClassKeyboard
If GetEventParameter_(Event, #kEventParamKeyMacCharCodes, #typeChar, 0, 4, 0, @KeyCode) = 0
SetGadgetText(1, Chr(KeyCode))
EndIf
EndSelect
If *NextEventHandler
CallNextEventHandler_(*NextEventHandler, Event)
EndIf
EndProcedure
Dim EventTypes.EventTypeSpec(2)
OpenWindow(0, 200, 200, 300, 70, "Detect mouse and key events")
TextGadget(0, 10, 10, WindowWidth(0) - 20, 20, "Press mouse button or key:", #PB_Text_Center)
TextGadget(1, 10, 35, WindowWidth(0) - 20, 20, "", #PB_Text_Border | #PB_Text_Center)
; ----- Install EventHandler
EventHandlerUPP = NewEventHandlerUPP_(@EventHandler())
; ----- Intercept mouse down events
EventTypes(0)\EventClass = #kEventClassMouse
EventTypes(0)\EventKind = #kEventMouseDown
; ----- Intercept raw key down events
EventTypes(1)\EventClass = #kEventClassKeyboard
EventTypes(1)\EventKind = #kEventRawKeyDown
InstallEventHandler_(GetWindowEventTarget_(WindowID(0)), EventHandlerUPP, 2, @EventTypes(), 0, 0)
Repeat
Until WaitWindowEvent() = #PB_Event_CloseWindow