get current focused window id using objective c

2019-06-11 13:21发布

问题:

how can i get current focused window id using objective c, the return value should be an int, help is highly appreciated! I just need to get the following line working

CGImageRef windowImage = CGWindowListCreateImage(CGRectNull, kCGWindowListOptionIncludingWindow, winNum, kCGWindowImageBoundsIgnoreFraming);

but no matter which window that i focus at, winNum is always 0.

回答1:

NSWindow *keyTarget = [[NSApplication sharedApplication] keyWindow];
NSInteger winNum = [keyTarget windowNumber];

or in one line:

[[[NSApplication sharedApplication] keyWindow] windowNumber];