如何在 cocoa 中获取鼠标单击事件元素

How can i get mouse click event element in cocoa

我在 macOS 中使用全局监视器接收点击事件。 NSEvent 给我坐标,但我需要获取 UIElement。

使用辅助功能 API,我可以获得焦点元素,但我需要完全不同的点击元素。例如,如果我点击一个文本区域,我会得到一个 AXTextArea 元素。如果我单击应用程序任务栏,焦点元素仍然是有意义的 AXTextArea。我想要与鼠标事件关联的元素。

我在网上找到了一个名为 accessibilityHitTest 的方法,它应该检索给定 NSPoint 下的 UIElement。我总是得到 null,所以我不确定这是否应该以这种方式工作。

也许还有另一个函数可以从屏幕中的给定点检索 UIElement?

这是我试过的方法:

NSEvent *event; // My event received from global monitoring
id clickedObject = [self accessibilityHitTest:event.locationInWindow];
//This give me an error because self is not a NSWindow.

NSEvent *event; // My event received from global monitoring
id clickedObject = 
[[NSApp keyWindow] accessibilityHitTest:event.locationInWindow];
//This give me null at every click.

也许这是不可能的,但我只是可以在鼠标单击下获得 UIElement 而不是聚焦的 UIElement。

您需要为此使用 AXUIElementCopyElementAtPosition()。请注意,您必须小心提供适当坐标系中的坐标。由于事件没有 window 关联(因为它用于不同的应用程序),NSEventlocationInWindow 使用 Cocoa 坐标系,原点在 [=21] =],y 向上增加。 AXUIElementCopyElementAtPosition() 在 Core Graphics 坐标系中获取坐标,原点在主显示器的 upper-left 中,y 向下递增。基本上,你会:

point.y = NSMaxY(NSScreen.screens[0].frame) - point.y;