addGlobalMonitorForEventsMatchingMask只返回鼠标位置 [英] addGlobalMonitorForEventsMatchingMask only returning mouse position

查看:721
本文介绍了addGlobalMonitorForEventsMatchingMask只返回鼠标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习Mac的代码。我一直是一个Java人一段时间,所以我希望我遇到的问题是一个简单的误解Cocoa。

I'm trying to learn to code for the Mac. I've been a Java guy for a while, so I hope the problem I'm running into is a simple misunderstanding of Cocoa.

我有以下代码:

-(IBAction)beginEventMonitor:(id)sender {
  _eventMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseUpMask)
  handler:^(NSEvent *incomingEvent) {
    //NSWindow *targetWindowForEvent = [incomingEvent window];
    NSLog(@"Got a mouse click event at %@", NSStringFromPoint([incomingEvent locationInWindow]));
    }];
}

-(IBAction)stopEventMonitor:(id)sender {
  if (_eventMonitor) {
    [NSEvent removeMonitor:_eventMonitor];
    _eventMonitor = nil;
  }
}

这是一个简单的钩子,单击发生在全局级别。处理程序是工作,但incomingEvent的内容似乎没有设置为任何东西。我可以找到的唯一有用的信息是鼠标在点击时的位置和窗口的windowId的点击。

This is a simple hook to tell me when a mouse click happens at a global level. The handler is working, but the contents of the incomingEvent don't seem to be set to anything. The only useful information that I can find is the location of the mouse at the time of the click, and the windowId of the window that was clicked in.

不应该我能获得更多的信息吗?我没有正确设置显示器?我真的想知道哪个窗口被点击,但我甚至不能找到一个方法将鼠标位置或windowId转换成有用的东西。

Shouldn't I be able to get more information? Am I not setting up the monitor correctly? I'd really like to be able to know which window was clicked in, but I can't even find a way to turn the mouse location or windowId into something useful.

推荐答案

您可以使用 CGWindow API(Leopard中的新功能)检索有关窗口的更多信息,例如:

You can retrieve more information about the window using the CGWindow APIs (new in Leopard), for example:

CGWindowID windowID = (CGWindowID)[incomingEvent windowNumber];
CFArrayRef a = CFArrayCreate(NULL, (void *)&windowID, 1, NULL);
NSArray *windowInfos = (NSArray *)CGWindowListCreateDescriptionFromArray(a);
CFRelease(a);
if ([windowInfos count] > 0) {
    NSDictionary *windowInfo = [windowInfos objectAtIndex:0];
    NSLog(@"Name:  %@", [windowInfo objectForKey:(NSString *)kCGWindowName]);
    NSLog(@"Owner: %@", [windowInfo objectForKey:(NSString *)kCGWindowOwnerName]);
    //etc.
}
[windowInfos release];

有很多信息(看看CGWindow.h或参考文档的可用键)。还有一些功能可以创建只有一个窗口的屏幕截图(甚至可以工作,如果它被部分覆盖的另一个窗口),很酷的东西!

There's lots of information there (look in CGWindow.h or refer to the docs for available keys). There are also functions to create screenshots of just one window (which even works if it's partially covered by another window), cool stuff!

这篇关于addGlobalMonitorForEventsMatchingMask只返回鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆