虚拟按键进入错误的应用程序 [英] Virtual keypress goes to wrong application

查看:86
本文介绍了虚拟按键进入错误的应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码将虚拟按键发送给具有其pid的进程

I have the following code to send virtual keypresses to a process given its pid

    NSRunningApplication* app = [NSRunningApplication
                                 runningApplicationWithProcessIdentifier: pid];
    [app activateWithOptions: (NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)];

    event1 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)cg_key_code, true);
    event2 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)cg_key_code, false);

    CGEventPost(kCGHIDEventTap, event1);
    CGEventPost(kCGHIDEventTap, event2);

我希望发送按键的过程迅速出现在前端,这与预期的一样.但是问题是,第一个按键将转到在我的应用程序出现之前位于前面的应用程序.经测试,[app isActive]首次返回false.按下第一个键后,一切正常.

The process that I wish to send keypresses to promptly comes to the front, as expected. But the problem is, the first keypress is going to the application which was at front before my application came front. When tested, [app isActive] returns false for the first time. After the first key, everything goes fine.

为什么会这样?即使我在关键事件之后发布,也将我的流程放在了最前面.

Why is this happening? Even though I am posting the key event after getting my process to the front.

推荐答案

由于文档没有说activateWithOptions:等待,并且当应用程序出现在前台时,它没有提供完成块来回调可以假定一旦检查了开关的有效性并发送了激活消息,该方法将立即返回.在这种情况与应用程序准备好接收用户输入之间不可避免地会有一些延迟.

As the documentation doesn't say that activateWithOptions: waits, and it doesn't provide a completion block to callback when the application has come to the foreground we can assume that the method will return as soon as the validity of the switch have been checked and the activation message sent. There will inevitably be some latency between this happening and the application actually being ready to receive user input.

尽管我们希望OS X可以缓冲用户输入,并在准备就绪时将其发送到应用程序,但在这种情况下始终会出现竞争状况,因此,谨慎地编写代码,以期望您需要等待.

While we could hope that OS X would buffer the user input and send it to the application when it's ready there will always be a race condition in this case so it's prudent to code with the expectation that you need to wait.

仅等待设定的时间并不是一个好主意,但是您可以使用工具来确定应该做什么以及持续多长时间-特别是使用isActive.另外,请谨慎检查activateWithOptions:的响应,以确保我们不会最终陷入僵局.

Just waiting for a set time isn't a great idea, but you have the tools to determine what you should do and for how long - specifically using isActive. Also, it's prudent to check the response of activateWithOptions: to ensure we don't end up deadlocked.

类似的东西:

if ([app activateWithOptions:(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)]) {

    while (![app isActive]) {
        app = [NSRunningApplication
                   runningApplicationWithProcessIdentifier: pid];
        [NSThread sleepForTimeInterval:0.05];
    }
}

// send key press events

这篇关于虚拟按键进入错误的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆