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.
- Note remove monitor