我知道这里有一些关于这个的问题,但我有这个类方法可以将击键发送到另一个进程,但它似乎部分工作。如果我发送一个@“mystring”的NSString,我会返回“mmmmmmmm”(即总是第一个字母乘以原始字符串的长度倍)。这是我的代码,请有人告诉我我缺少什么。顺便说一下,字符的 NSLog 显示缓冲区变量中的正确字符。我看过的其他问题 1. CGEventCreateKeyboardEvent 和 CGEventTapLocation 2.- CGEventPostToPSN - 如何发送具有不同键盘区域设置的键?
+(void)writeString:(NSString *)valueToSet withFlags:(int)flags intoProcess:(ProcessSerialNumberPtr) process
{
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStatePrivate);
CGEventRef keyEventDown = CGEventCreateKeyboardEvent(source, 1, true);
CGEventRef keyEventUp = CGEventCreateKeyboardEvent(source, 1, false);
CGEventSetFlags(keyEventDown,0);
CGEventSetFlags(keyEventUp,0);
UniChar buffer;
CFRelease(source);
for (int i = 0; i < [valueToSet length]; i++) {
buffer = [valueToSet characterAtIndex:i];
NSLog(@" %i place Character: %c",i,buffer);
CGEventKeyboardSetUnicodeString(keyEventDown, 1, &buffer);
CGEventKeyboardSetUnicodeString(keyEventUp, 1, &buffer);
CGEventSetFlags(keyEventDown,flags);
CGEventPostToPSN(process, keyEventDown);
[NSThread sleepForTimeInterval: 0.01];
CGEventSetFlags(keyEventUp,flags);
CGEventPostToPSN(process, keyEventUp);
[NSThread sleepForTimeInterval: 0.01];
}
CFRelease(keyEventUp);
CFRelease(keyEventDown);
}