在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.
- 注意移除监视器