Skip to content

Instantly share code, notes, and snippets.

@kylemcdonald
Created June 22, 2012 21:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylemcdonald/2975288 to your computer and use it in GitHub Desktop.
Save kylemcdonald/2975288 to your computer and use it in GitHub Desktop.
openFrameworks utilities for working with the mouse and screen even when an app does not have focus
#pragma once
#include "ofGraphics.h"
#include "ofImage.h"
class ofGlobalListener {
public:
ofGlobalListener();
virtual void globalMouseDown(float x, float y) = 0;
};
void ofRegisterGlobalEvents(ofGlobalListener* app);
ofPoint ofGetGlobalMousePosition();
void ofGrabGlobalScreen(ofImage& img, ofRectangle& region);
#include "ofxGlobalUtils.h"
#include "ofMain.h"
#ifdef TARGET_OSX
#include <Cocoa/Cocoa.h>
#endif
ofGlobalListener::ofGlobalListener() {
ofRegisterGlobalEvents(this);
}
void ofRegisterGlobalEvents(ofGlobalListener* app) {
#ifdef TARGET_OSX
static NSPoint point;
[NSEvent
addGlobalMonitorForEventsMatchingMask: (NSLeftMouseDownMask | NSRightMouseDownMask | NSOtherMouseDownMask)
handler: ^(NSEvent *incomingEvent) {
point = [NSEvent mouseLocation];
point.y = ofGetScreenHeight() - point.y;
app->globalMouseDown(point.x, point.y);
}
];
#endif
}
ofPoint ofGetGlobalMousePosition() {
#ifdef TARGET_OSX
Point mouse;
GetGlobalMouse(&mouse);
return ofPoint(mouse.h, mouse.v);
#endif
}
void ofGrabGlobalScreen(ofImage& img, ofRectangle& region) {
region.width = MAX((int) region.width, 1);
region.height = MAX((int) region.height, 1);
#ifdef TARGET_OSX
static int bytesPerPixel = 4;
img.allocate(region.width, region.height, OF_IMAGE_COLOR_ALPHA);
CGImageRef cgImage = CGWindowListCreateImage(
CGRectMake(region.x, region.y, region.width, region.height),
kCGWindowListOptionOnScreenOnly,
kCGNullWindowID,
kCGWindowImageDefault);
CGContextRef spriteContext = CGBitmapContextCreate(
img.getPixels(), region.width, region.height,
CGImageGetBitsPerComponent(cgImage),
region.width * bytesPerPixel,
CGImageGetColorSpace(cgImage),
kCGImageAlphaPremultipliedLast);
CGContextDrawImage(spriteContext, CGRectMake(0, 0, (CGFloat) region.width, (CGFloat) region.height), cgImage);
CGContextRelease(spriteContext);
CGImageRelease(cgImage);
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment