Windows上很久以前就有按键精灵,Mac上也可以实现类似功能,以下一个小demo演示了如何去实现鼠标和键盘操作的自动化。
一、新建Mac应用,代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSButton* button = [[NSButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
button.target = self;
button.action = @selector(buttonClick);
[self.view addSubview:button];
[button mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.mas_equalTo(100);
make.right.bottom.mas_equalTo(-100);
}];
}
- (void)buttonClick
{
CGPoint pt = CGPointMake(216, 80);
PostMouseEvent(kCGMouseButtonLeft, kCGEventLeftMouseDown, pt);
PostMouseEvent(kCGMouseButtonLeft, kCGEventLeftMouseUp, pt);
sleep(2);
[self writeString:@"Hello" withFlags:0];
}
void PostMouseEvent(CGMouseButton button, CGEventType type, const CGPoint point)
{
CGEventRef theEvent = CGEventCreateMouseEvent(NULL, type, point, button);
CGEventSetType(theEvent, type);
CGEventPost(kCGHIDEventTap, theEvent);
CFRelease(theEvent);
}
-(void)writeString:(NSString *)valueToSet withFlags:(int)flags
{
UniChar buffer;
CGEventRef keyEventDown = CGEventCreateKeyboardEvent(NULL, 1, true);
CGEventRef keyEventUp = CGEventCreateKeyboardEvent(NULL, 1, false);
CGEventSetFlags(keyEventDown,0);
CGEventSetFlags(keyEventUp,0);
for (int i = 0; i < [valueToSet length]; i++) {
[valueToSet getCharacters:&buffer range:NSMakeRange(i, 1)];
CGEventKeyboardSetUnicodeString(keyEventDown, 1, &buffer);
CGEventSetFlags(keyEventDown,flags);
CGEventPost(kCGSessionEventTap, keyEventDown);
CGEventKeyboardSetUnicodeString(keyEventUp, 1, &buffer);
CGEventSetFlags(keyEventUp,flags);
CGEventPost(kCGSessionEventTap, keyEventUp);
}
CFRelease(keyEventUp);
CFRelease(keyEventDown);
}
二、通过AppleScript实现:
activate application "Finder"
tell application "System Events"
tell process "Finder"
click at {15, 2}
end tell
end tell
网友评论