Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

A quick google search showed me that this method only works inside of NSWindows. However, there most be some way to detect if mouse position is pressed, and if so; how can i do it?

like image 367
Freddy Avatar asked Dec 19 '25 04:12

Freddy


1 Answers

You can use 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;
}
like image 145
Sergey Neskoromny Avatar answered Dec 20 '25 19:12

Sergey Neskoromny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!