我想知道如何获取鼠标指针当前所在位置的像素颜色,与OS X / macOS有关的。
我编写了一个控制台应用程序,因此没有窗口可以叠加或其他什么东西。
当我构建和运行程序时,它应该给我一个控制台日志,显示鼠标指针当前所在位置的颜色。这可能吗?
我想知道如何获取鼠标指针当前所在位置的像素颜色,与OS X / macOS有关的。
我编写了一个控制台应用程序,因此没有窗口可以叠加或其他什么东西。
当我构建和运行程序时,它应该给我一个控制台日志,显示鼠标指针当前所在位置的颜色。这可能吗?
以这个问题和答案为起点,这是一个完全功能的命令行程序。
// 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;
}