我整天点击鼠标会导致肌腱炎。
过去我使用Karabiner重新映射fn
键来模拟鼠标左键。但是它不适用于Sierra。
我尝试在Cocoa中完成此操作,当我按下并释放fn
时,它正确执行鼠标按下/向上。
但是它不能处理双击/三击。
同样在拖动时(例如拖动窗口或选择一些文本),直到我按键完成时才会在视觉上发生任何事情,然后它就会完成。
如何调整我的代码来实现它?
首先我创建一个事件点击:
- (BOOL)tapEvents
{
_modifiers = [NSEvent modifierFlags];
if ( ! _eventTap ) {
NSLog( @"Initializing an event tap." );
// kCGHeadInsertEventTap -- new event tap should be inserted before
// any pre-existing event taps at the same location,
_eventTap = CGEventTapCreate( kCGHIDEventTap, // kCGSessionEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionDefault,
CGEventMaskBit( kCGEventKeyDown )
| CGEventMaskBit( kCGEventFlagsChanged )
| CGEventMaskBit( NSSystemDefined )
,
(CGEventTapCallBack)_tapCallback,
(__bridge void *)(self));
if ( ! _eventTap ) {
NSLog(@"unable to create event tap. must run as root or "
"add privlidges for assistive devices to this app.");
return NO;
}
}
CGEventTapEnable( _eventTap, YES );
return [self isTapActive];
}
现在我实现了回调:
CGEventRef _tapCallback(
CGEventTapProxy proxy,
CGEventType type,
CGEventRef event,
Intercept* listener
)
{
//Do not make the NSEvent here.
//NSEvent will throw an exception if we try to make an event from the tap timout type
@autoreleasepool {
if( type == kCGEventTapDisabledByTimeout ) {
NSLog(@"event tap has timed out, re-enabling tap");
[listener tapEvents];
return nil;
}
if( type != kCGEventTapDisabledByUserInput ) {
return [listener processEvent:event];
}
}
return event;
}
最后,我实现了一个processEvent
,它将通过除fn键上/下之外的任何事件,它将被转换为鼠标左/右:
- (CGEventRef)processEvent:(CGEventRef)cgEvent
{
//NSLog( @"- - - - - - -" );
NSEvent* event = [NSEvent eventWithCGEvent:cgEvent];
//NSLog(@"%d,%d", event.data1, event.data2);
//NSEventType type = [event type];
NSUInteger m = event.modifierFlags &
( NSCommandKeyMask | NSAlternateKeyMask | NSShiftKeyMask | NSControlKeyMask | NSAlphaShiftKeyMask | NSFunctionKeyMask );
NSUInteger flags_changed = _modifiers ^ m;
_modifiers = m;
switch( event.type ) {
case NSFlagsChanged:
{
assert(flags_changed);
//NSLog(@"NSFlagsChanged: %d, event.modifierFlags: %lx", event.keyCode, event.modifierFlags);
if( flags_changed & NSFunctionKeyMask ) {
bool isDown = _modifiers & NSFunctionKeyMask;
CGEventType evType = isDown ? kCGEventLeftMouseDown : kCGEventLeftMouseUp;
CGPoint pt = [NSEvent mouseLocation];
CGPoint mousePoint = CGPointMake(pt.x, [NSScreen mainScreen].frame.size.height - pt.y);
CGEventRef theEvent = CGEventCreateMouseEvent(NULL, evType, mousePoint, kCGMouseButtonLeft);
CGEventSetType(theEvent, evType);
CGEventPost(kCGHIDEventTap, theEvent);
CFRelease(theEvent);
//return theEvent;
}
break;
}
}
_lastEvent = [event CGEvent];
CFRetain(_lastEvent); // must retain the event. will be released by the system
return _lastEvent;
}
编辑:Performing a double click using CGEventCreateMouseEvent()