OSX assign left mouse click to a keyboard key

二次信任 提交于 2019-12-12 08:58:16

问题


I would like to be able to assign a key on my keyboard to be equivalent to a left mouse click.

Ideally it needs to act such that holding the key down is also equivalent to holding the left mouse button down.

I'd like this capability as a user, additionally a programmatic solution (cocoa/applescript etc) would be great too.


回答1:


Not exactly what you want, but in the System preferences -> Universal access you can turn on mouse keys - and with them you can move (and click) mouse by keyboard. docs here:

  • http://docs.info.apple.com/article.html?path=Mac/10.6/en/cdb_moskys.html
  • http://docs.info.apple.com/article.html?path=Mac/10.6/en/8565.html
  • http://docs.info.apple.com/article.html?artnum=61472

Or, With the "ControllerMate.app" is possible to do this, but it is commercial app.




回答2:


This can be done by writing some code:

Write a global handler to receive the type of event you want to watch

[NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyDownMask 
                                       handler:^(NSEvent *event){
                                           NSLog(@"%i", [event keyCode]);

                                           //todo invoke mouse clicking code;
                                       }];

Then write the mouse click code:

// get current mouse pos
CGEventRef ourEvent = CGEventCreate(NULL);
CGPoint point = CGEventGetLocation(ourEvent);
NSLog(@"Location? x= %f, y = %f", (float)point.x, (float)point.y);

// perform a click
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventRef theEvent = CGEventCreateMouseEvent(source, kCGEventLeftMouseDown, point, kCGMouseButtonLeft);
CGEventSetType(theEvent, kCGEventLeftMouseDown);
CGEventPost(kCGHIDEventTap, theEvent);
CFRelease(theEvent);


来源:https://stackoverflow.com/questions/6312480/osx-assign-left-mouse-click-to-a-keyboard-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!