macOS - monitor global events

In macOS development, we often have some of the mouse or keyboard to monitor the needs of global events, such as pressing the option key, the display view

of code:

- (void)awakeFromNib
{
   [super awakeFromNib];
   if (self) {
       
       __weak typeof(self) weakSelf = self;
      self.globalEventMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:NSEventMaskFlagsChanged handler:^(NSEvent * _Nonnull event) {
           NSLog(@"Victor-Debug:  Global");
//           [NSEvent removeMonitor:weakSelf.globalEventMonitor];
       }];
       
       self.localEventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskFlagsChanged handler:^NSEvent * _Nullable(NSEvent * event) {
           NSLog(@"Victor-Debug:  Local");
//            [NSEvent removeMonitor:weakSelf.localEventMonitor];
           return event;
       }];
       
   }
}

- (void)dealloc
{
   [NSEvent removeMonitor:self.localEventMonitor];
   [NSEvent removeMonitor:self.globalEventMonitor];
}

Adding a callback system, execution conditions according to the parameter block.

  1. Note remove monitor
Published 34 original articles · won praise 20 · views 20000 +

Guess you like

Origin blog.csdn.net/ZhangWangYang/article/details/95952046