CGEvent NSKeyDown 仅在应用程序位于最前面时才起作用?
我正在尝试自动化一些任务(没有 applescript 支持),所以我必须使用 CGEvents 并发布这些事件。鼠标单击工作正常,但 NSKeyDown(输入)仅在我单击扩展坞中的应用程序时才有效(这使其成为最前面的应用程序)... 到目前为止,这是我的代码:
for (NSDictionary *dict in windowList) {
NSLog(@"%@", dict);
if ([[dict objectForKey:@"kCGWindowName"] isEqualToString:@"Some Window..."]) {
WIDK = [[dict objectForKey:@"kCGWindowNumber"] intValue];
break;
};
}
CGEventRef CGEvent;
NSEvent *customEvent;
customEvent = [NSEvent keyEventWithType:NSKeyDown
location:NSZeroPoint
modifierFlags:0
timestamp:1
windowNumber:WIDK
context:nil
characters:nil
charactersIgnoringModifiers:nil
isARepeat:NO
keyCode:36];
CGEvent = [customEvent CGEvent];
for (int i=0; i <5; i++) {
sleep(3);
CGEventPostToPSN(&psn, CGEvent);
NSLog(@"posted the event");
}
CFRelease(eOne);
我在循环中使用 posteventtopsn 的原因是出于测试目的(我只需要它发送一次)。当程序处于循环中时,如果我将应用程序激活到最前面,则该事件可以正常工作。
我做错了什么?如果它在后台有什么办法可以工作吗?谢谢。
I am trying to automate some tasks (there's no applescript support) so I have to use CGEvents and post these events. Mouse clicking works fine, but NSKeyDown (enter) only works if I click on the app in the dock(which makes it front most app)...
Here's my code so far:
for (NSDictionary *dict in windowList) {
NSLog(@"%@", dict);
if ([[dict objectForKey:@"kCGWindowName"] isEqualToString:@"Some Window..."]) {
WIDK = [[dict objectForKey:@"kCGWindowNumber"] intValue];
break;
};
}
CGEventRef CGEvent;
NSEvent *customEvent;
customEvent = [NSEvent keyEventWithType:NSKeyDown
location:NSZeroPoint
modifierFlags:0
timestamp:1
windowNumber:WIDK
context:nil
characters:nil
charactersIgnoringModifiers:nil
isARepeat:NO
keyCode:36];
CGEvent = [customEvent CGEvent];
for (int i=0; i <5; i++) {
sleep(3);
CGEventPostToPSN(&psn, CGEvent);
NSLog(@"posted the event");
}
CFRelease(eOne);
The reason why I have posteventtopsn in a loop is for testing purposes (I just need it to send it once). While the program is in the loop, if I activate my app to front most, then the event works fine.
What am I doing wrong? Is there a way it can work if it in background? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是将键盘事件发布到最前面的应用程序的更好方法:
CGEventPost 允许您确定事件发布的位置。我最近使用此代码允许某人远程控制我笔记本电脑上的 PPT 演示文稿。 (字符 124 是右箭头键。)
请注意,您应该在发布事件后释放该事件。
您可以使用 CGEventPostToPSN 发送到特定应用程序(例如,不是前端应用程序)。
Here is a better way to post keyboard events to the front-most application:
CGEventPost lets you determine where the event is posted. I used this code recently to allow someone to remotely control a PPT presentation on my laptop. (Character 124 is the right arrow key.)
Note that you should be freeing the event after posting it.
You can send to a specific app (eg not the front app) by using CGEventPostToPSN.
我认为这是因为您使用“WIDK”作为参数 windowNumber 创建一个 NSEvent ,而 WIDK 仅与您的应用程序相关。
i think it's because you create a NSEvent using "WIDK" for parameter windowNumber , and WIDK is related to your app only.