macOS - 监听全局事件

在macOS开发中,我们时常会有一些要监听鼠标或者键盘全局事件的需求, 比如按下option键,显示view

代码:

- (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];
}

在系统中加入一个回调,根据参数条件执行block.

  1. 注意移除监视器
发布了34 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/ZhangWangYang/article/details/95952046
今日推荐