Created
June 22, 2012 21:24
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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