Re: EventHandler to detect key presses and mouse clicks
Posted: Sun Oct 21, 2012 6:20 pm
It's not really tricky. It may just be a bit hard to understand if you are just starting out with Cocoa functionalityjesperbrannmark wrote:Its really tricky to understand this.. and why didn't Apple just choose to use Purebasic to begin with instead of fiddling with this Xcode beast?

Why Apple didn't just choose PureBasic. Very good question

Anyway ... does this help you out ?
Code: Select all
#NSLeftMouseUp = 2
#NSRightMouseUp = 4
#NSMouseMoved = 5
#NSKeyDown = 10
#NSKeyUp = 11
#NSScrollWheel = 22
#NSAlphaShiftKeyMask = 1 << 16
#NSShiftKeyMask = 1 << 17
#NSControlKeyMask = 1 << 18
#NSAlternateKeyMask = 1 << 19
#NSCommandKeyMask = 1 << 20
EnableExplicit
Global sharedApplication = CocoaMessage(0, 0, "NSApplication sharedApplication")
Define currentEvent, type, modifierFlags, keyCode
Define clickCount, location.NSPoint, deltaX.CGFloat, deltaY.CGFloat
Define Event
If OpenWindow(0, 0, 0, 320, 170, "Events example", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
EditorGadget(0, 10, 10, 300, 100, #PB_Editor_ReadOnly)
Repeat
Event = WaitWindowEvent()
currentEvent = CocoaMessage(0, sharedApplication, "currentEvent")
If currentEvent
type = CocoaMessage(0, currentEvent, "type")
modifierFlags = CocoaMessage(0, currentEvent, "modifierFlags")
ClearGadgetItems(0)
; mouse events
If type = #NSLeftMouseUp
clickCount = CocoaMessage(0, currentEvent, "clickCount")
SetGadgetText(0, "Left mouse " + Str(clickCount) + "x clicked")
EndIf
If type = #NSRightMouseUp
clickCount = CocoaMessage(0, currentEvent, "clickCount")
SetGadgetText(0, "Right mouse " + Str(clickCount) + "x clicked")
EndIf
If type = #NSMouseMoved
CocoaMessage(@location, currentEvent, "locationInWindow")
SetGadgetText(0, "Mouse moved to (" + StrF(location\x, 1) + "," + StrF(WindowHeight(0)-location\y, 1) + ")"); use WindowHeight() to flip y coordinate
EndIf
If type = #NSScrollWheel
CocoaMessage(@deltaX, currentEvent, "deltaX")
CocoaMessage(@deltaY, currentEvent, "deltaY")
SetGadgetText(0, "Mouse wheel delta (" + StrF(deltaX, 1) + "," + StrF(deltaY, 1) + ")")
EndIf
; keyboard events
If type = #NSKeyDown
keyCode = CocoaMessage(0, currentEvent, "keyCode")
SetGadgetText(0, "Key down with code : " + Str(keyCode))
EndIf
If type = #NSKeyUp
keyCode = CocoaMessage(0, currentEvent, "keyCode")
SetGadgetText(0, "Key up with code : " + Str(keyCode))
EndIf
; key modifiers
If modifierFlags & #NSAlphaShiftKeyMask
AddGadgetItem(0, -1, "Caps lock is on")
Else
AddGadgetItem(0, -1, "Caps lock is off")
EndIf
If modifierFlags & #NSShiftKeyMask
AddGadgetItem(0, -1, "Shift key is pressed")
EndIf
If modifierFlags & #NSControlKeyMask
AddGadgetItem(0, -1, "Ctrl key is pressed")
EndIf
If modifierFlags & #NSAlternateKeyMask
AddGadgetItem(0, -1, "Alt key is pressed")
EndIf
If modifierFlags & #NSCommandKeyMask
AddGadgetItem(0, -1, "Cmd key is pressed")
EndIf
EndIf
Until Event = #PB_Event_CloseWindow
EndIf