Catch mouse events with CGEvent.tapCreate in Swift on MacOS

1k views Asked by At

I am novice Swift coder trying to catch mouse events as well as keyboard events. It seems I am only doing the latter. The main goal is to allow for «tap-to-click» with Magic Mouse 2 and avoid its loud clicking sound.

Fully working sample at https://github.com/creasty/Keyboard/blob/master/keyboard/AppDelegate.swift

let eventMask = 
    (1 << CGEventType.keyDown.rawValue) | 
    (1 << CGEventType.keyUp.rawValue) | 
    (1 << CGEventType.leftMouseDown.rawValue) | 
    (1 << CGEventType.leftMouseUp.rawValue)

guard let eventTap = CGEvent.tapCreate(
    tap: .cghidEventTap,
    place: .headInsertEventTap,
    options: .defaultTap,
    eventsOfInterest: CGEventMask(eventMask),
    callback: appComponent.eventTapCallback,
    userInfo: nil
) else {
    fatalError("Failed to create event tap")
}

Keyboard presses are caught alright, but no reaction to mouse clicks. Please advise. Thanks.

Xcode Version 12.5.1 (12E507) on MacOS 11.5.2

1

There are 1 answers

0
Andreas F On

Thanks to helpful feedback from @Willeke and others, we arrived at the following solution:

diff --git a/keyboard/AppComponent.swift b/keyboard/AppComponent.swift
index 961a81b..abb2f63 100644
--- a/keyboard/AppComponent.swift
+++ b/keyboard/AppComponent.swift
@@ -20,6 +20,8 @@ final class AppComponent {
             if let manager = _eventManager {
                 return manager.handle(proxy: proxy, cgEvent: event)
             }
+        case .leftMouseDown:
+            print("leftMouseDown")
         default:
             break
         }
diff --git a/keyboard/AppDelegate.swift b/keyboard/AppDelegate.swift
index bc39af6..dc16658 100644
--- a/keyboard/AppDelegate.swift
+++ b/keyboard/AppDelegate.swift
@@ -70,8 +70,8 @@ private extension AppDelegate {
     }
 
     func setupEventTap() {
-        let eventMask = (1 << CGEventType.keyDown.rawValue) | (1 << CGEventType.keyUp.rawValue)
-
+        let eventMask = (1 << CGEventType.keyDown.rawValue) | (1 << CGEventType.keyUp.rawValue) | (1 << CGEventType.leftMouseDown.rawValue)
+        
         guard let eventTap = CGEvent.tapCreate(
             tap: .cghidEventTap,
             place: .headInsertEventTap,