简体   繁体   English

如何检测鼠标是否在可可窗口外?

[英]How can I detect if mouse is down outside of window in cocoa?

As the titles says i wonder if it is possible to detect if the mouse button is down.正如标题所说,我想知道是否可以检测鼠标按钮是否按下。 I tried putting this code in my app delegate.m but with no success.我尝试将此代码放在我的应用程序 delegate.m 中,但没有成功。

- (void)mouseDown:(NSEvent *)theEvent
{
    NSLog(@"hello world!");
}

A quick google search showed me that this method only works inside of NSWindows.一个快速的谷歌搜索告诉我这个方法只适用于 NSWindows 内部。 However, there most be some way to detect if mouse position is pressed, and if so;然而,大多数有一些方法可以检测鼠标位置是否被按下,如果是的话; how can i do it?我该怎么做?

You can use NSEvent addGlobalMonitorForEventsMatchingMask :您可以使用NSEvent addGlobalMonitorForEventsMatchingMask

define in your control:在您的控制中定义:

id mouseEventMonitor;

-(id)init{

    mouseEventMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDownMask | NSRightMouseDownMask | NSOtherMouseDownMask)
                                           handler:^(NSEvent *event){

        NSLog(@"theEvent->%@",event);

        //here you will receive the all mouse DOWN events
        if (event.modifierFlags & NSCommandKeyMask)
        {
          NSLog(@"theEvent1->%@",event);
        }else{
          NSLog(@"theEvent2->%@",event);
        }

    }];

    return self;
}

Cocoa Event Monitors are the way to go.可可事件监视器是要走的路。
You can use them to track pretty much every kind of mouse event outside of your view hierarchy.您可以使用它们来跟踪视图层次结构之外的几乎所有类型的鼠标事件。

Check out the documentation in the Cocoa Event Handling Guide for information on how to use them and similar topics here on SO like查看Cocoa 事件处理指南中的文档,了解有关如何使用它们的信息以及 SO 上的类似主题

Although you mention mouseDown in your question and have accepted an answer that describes how to set up a monitor, as far as I can tell from the rest of the question, you don't actually need an event that fires when the mouse button is pressed, but instead just want to check if a mouse button is currently pressed.尽管您在问题中提到了mouseDown并接受了描述如何设置监视器的答案,但据我从问题的其余部分可以看出,您实际上并不需要按下鼠标按钮时触发的事件,而只是想检查当前是否按下了鼠标按钮。

NSEvent has a class property you can use for this: NSEvent有一个类属性,您可以使用它:

[NSEvent pressedMouseButtons]

This returns the indices of the currently pressed mouse buttons:这将返回当前按下的鼠标按钮的索引:

A return value of 1 << 0 corresponds to the left mouse button, 1 << 1 corresponds to the right mouse button, 1<< n, n >=2 correspond to other mouse buttons.返回值 1 << 0 对应鼠标左键, 1 << 1 对应鼠标右键, 1<< n, n >=2 对应其他鼠标按键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM