1. 监听全局键盘事件
在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.
- 最后要注意移除监视器
2. 判断鼠标是否按下
1). 在NSView中添加flag: isMouseDown
在下面的API中设置flag值
- (void)mouseDown:(NSEvent *)event;
- (void)rightMouseDown:(NSEvent *)event;
- (void)otherMouseDown:(NSEvent *)event;
- (void)mouseUp:(NSEvent *)event;
- (void)rightMouseUp:(NSEvent *)event;
2). 利用NSEvent的类变量
open class var pressedMouseButtons: Int { get }
1:鼠标左键被按下
2:鼠标右键键被按下
3:鼠标左键和右键同时被按下