'Detect color under macOS mouse cursor
I want to know how to get the color of the pixel where the OS X / macOS mouse pointer currently is located.
I programmed a console application, so I have no window to overlay or something else.
When I build and run the program, it should give me a console log of the color where my mouse pointer currently is. Is that possible?
Solution 1:[1]
Using this question and answer as a starting point, this is a fully functional command line program.
// To build and run, save this file as main.m, then:
//
// clang -framework Foundation -framework Cocoa main.m
// ./a.out
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
int main(int argc, const char *argv[]) {
CGDirectDisplayID mainDisplayID = CGMainDisplayID();
// NSLog(@"Main display id=%d", mainDisplayID);
while (true) {
@autoreleasepool {
CGPoint cursor = CGEventGetLocation(CGEventCreate(NULL));
// NSLog(@"Mouse pos: (%f, %f)", cursor.x, cursor.y);
CGRect rect = CGRectMake(cursor.x, cursor.y, 1, 1);
CGImageRef image = CGDisplayCreateImageForRect(mainDisplayID, rect);
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithCGImage:image];
CGImageRelease(image);
NSColor *color = [bitmap colorAtX:0 y:0];
NSLog(@"%@", color);
[bitmap release];
}
}
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Andrey Mishchenko |