Limit mouse movement to an area in OS X without jitter

I would like to limit the movement of the mouse to a specific rectangular area of ​​the screen in OS X 10.11. I changed the MouseTools code (below) to do this, but it trembles when you hit the edge of the screen. How can I get rid of this trembling?

// gcc -Wall constrain.cpp -framework ApplicationServices -o constrain

#include <ApplicationServices/ApplicationServices.h>

int main (int argc, const char * argv[]) {
    if(argc != 5) {
        printf("Usage: constrain left top right bottom\n");
        return 0;
    }
    int leftBound = strtol(argv[1], NULL, 10);
    int topBound = strtol(argv[2], NULL, 10);
    int rightBound = strtol(argv[3], NULL, 10);
    int bottomBound = strtol(argv[4], NULL, 10);
    CGEventTapLocation tapLocation = kCGHIDEventTap;
    CGEventSourceRef sourceRef = CGEventSourceCreate(kCGEventSourceStatePrivate);
    while(true) {
        CGEventRef mouseEvent = CGEventCreate(NULL);
        CGPoint mouseLoc = CGEventGetLocation(mouseEvent);
        int x = mouseLoc.x, y = mouseLoc.y;
        if(x < leftBound || x > rightBound || y < topBound || y > bottomBound) {
            if(x < leftBound) x = leftBound;
            if(x > rightBound) x = rightBound;
            if(y < topBound) y = topBound;
            if(y > bottomBound) y = bottomBound;
            CGEventRef moveMouse = CGEventCreateMouseEvent(sourceRef, kCGEventMouseMoved, CGPointMake(x, y), 0);
            CGEventPost(tapLocation, moveMouse);
            CFRelease(moveMouse);
        }
        CFRelease(mouseEvent);
        usleep(8*1000); // 8ms, ~120fps
    }
    CFRelease(sourceRef);
    return 0;
}

, : , , , CGEventTapCreate. : " . , CGEventSetLocation(event, newLocation)". , ( ). , , - CGEventPost CGWarpMouseCursorPosition. kCGHIDEventTap kCGSessionEventTap, , . , , , . CGEventSetLocation CGEventSetIntegerValueField (, ), x y 0, .

, CGEventPost CGWarpMouseCursorPosition CGEventCallback, " " , .

+4
1

Wine Mac. .

, , CGAssociateMouseAndMouseCursorPosition(false). , , 1x1 .

, , . , , . CGWarpMouseCursorPosition() .

, . . . , . , , , . ( ), warp. . Etc.

. CGWarpMouseCursorPosition() . , , , , . Unchecked, , .

, , , , . , , . , , , .

+3
source

Source: https://habr.com/ru/post/1662497/


All Articles