Skip to content

Add mouse support. #29

@razterizer

Description

@razterizer

There are three separate solutions for MacOS, Linux and Windows respectively. I have working code for MacOS for starters (from ChatGPT):

#include <iostream>
#include <ApplicationServices/ApplicationServices.h>

using namespace std;

// Global cursor position
int cursor_x = 40;
int cursor_y = 12;

// Callback function to handle mouse events
CGEventRef eventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {
    if (type == kCGEventMouseMoved || type == kCGEventLeftMouseDragged || type == kCGEventRightMouseDragged) {
        CGPoint location = CGEventGetLocation(event);
        cursor_x = static_cast<int>(location.x);
        cursor_y = static_cast<int>(location.y);

        std::cout << "(x, y) = (" << cursor_x << ", " << cursor_y << ")\n";
    }
    return event;
}

int main() {
    // Create an event tap
    CGEventMask eventMask = (1 << kCGEventMouseMoved) | (1 << kCGEventLeftMouseDragged) | (1 << kCGEventRightMouseDragged);
    CFMachPortRef eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, 0, eventMask, eventCallback, nullptr);

    if (!eventTap) {
        cerr << "Failed to create event tap" << endl;
        return -1;
    }

    // Create a run loop source and add it to the current run loop
    CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);

    // Enable the event tap
    CGEventTapEnable(eventTap, true);

    // Run the loop to start receiving events
    CFRunLoopRun();

    // Cleanup
    CFRelease(eventTap);
    CFRelease(runLoopSource);

    return 0;
}

This is built using:

g++ -o mouse_test mouse_test.cpp -framework ApplicationServices

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions