我正在使用Cocoa/Objective,我想问您是否可以从不活动的窗口获取窗口信息,如pid、窗口名称。我的确切意思是,在有两个不同任务的非全屏(或最大化)窗口A和B的情况下,假设Chrome(A)和Firefox(B)具有活动窗口A和鼠标光标在窗口B之上,我能不需要单击窗口B并将其带到前台就可以获得这样的信息吗?
我注意到,例如,在一个不活动的窗口中滚动滚动的上下文就像它在前台一样,所以我的猜测是这是可行的。
任何小费都会很受欢迎的。
谢谢
发布于 2014-12-21 13:42:15
我将回答我自己的问题:使用可访问性api & carbon a)注册一个广泛的事件是可能的:
AXUIElementRef _systemWideElement = AXUIElementCreateSystemWide();
(B)将碳转化为屏幕点
- (CGPoint)carbonScreenPointFromCocoaScreenPoint:(NSPoint)cocoaPoint {
NSScreen *foundScreen = nil;
CGPoint thePoint;
for (NSScreen *screen in [NSScreen screens]) {
if (NSPointInRect(cocoaPoint, [screen frame])) {
foundScreen = screen;
}
}
if (foundScreen) {
CGFloat screenMaxY = NSMaxY([foundScreen frame]);
thePoint = CGPointMake(cocoaPoint.x, screenMaxY - cocoaPoint.y - 1);
} else {
thePoint = CGPointMake(0.0, 0.0);
}
return thePoint;
}
c)鼠标下获取进程
NSPoint cocoaPoint = [NSEvent mouseLocation];
if (!NSEqualPoints(cocoaPoint, _lastMousePoint)) {
CGPoint pointAsCGPoint = [self carbonScreenPointFromCocoaScreenPoint:cocoaPoint];
AXUIElementRef newElement = NULL;
if (AXUIElementCopyElementAtPosition( _systemWideElement, pointAsCGPoint.x, pointAsCGPoint.y, &newElement ) == kAXErrorSuccess) {
NSLog(@"%@",newElement);
}
_lastMousePoint = cocoaPoint;
}
给https://developer.apple.com/library/mac/samplecode/UIElementInspector/Introduction/Intro.html的学分
nslog给出了类似于 {pid=39429}的内容。
ps aux | grep 39429
:39429 0.2 5.5 5109480 916500 ?? U 1:57PM 3:34.67 /Applications/Xcode.app/Contents/MacOS/Xcode
发布于 2022-11-11 21:16:20
使用[NSWindow windowNumberAtPoint:belowWindowWithWindowNumber:]
应该比使用另一个答案中提到的AXUI
API快得多。
下面是我在鼠标指针下获取应用程序的实现,但您也可以通过这种方式获取各种其他信息,比如PID:
+ (NSRunningApplication * _Nullable)appUnderMousePointerWithEvent:(CGEventRef _Nullable)event {
/// Get PID under mouse pointer
pid_t pidUnderPointer = -1; /// I hope -1 is actually unused?
NSPoint pointerLoc = [NSEvent mouseLocation];
CGWindowID windowNumber = (CGWindowID)[NSWindow windowNumberAtPoint:pointerLoc belowWindowWithWindowNumber:0];
NSArray *windowInfo = (__bridge_transfer NSArray *)CGWindowListCopyWindowInfo(kCGWindowListOptionIncludingWindow, windowNumber);
if (windowInfo.count > 0) {
pidUnderPointer = [windowInfo[0][(__bridge NSString *)kCGWindowOwnerPID] intValue];
}
/// Get runningApplication
NSRunningApplication *appUnderMousePointer = [NSRunningApplication runningApplicationWithProcessIdentifier:pidUnderPointer];
return appUnderMousePointer;
}
https://stackoverflow.com/questions/27584963
复制相似问题