通过流程ID将KeyEvent发送到目标窗口 [英] Send KeyEvent to a Target window via process Id

查看:152
本文介绍了通过流程ID将KeyEvent发送到目标窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个关键事件(cmd + r用于刷新浏览器窗口),并为我要定位的窗口传递进程ID.假设

I need to create a key event (cmd + r for refresh for the browser window) and pass the process Id for the window I'm trying to target. Let's say

    let customEvent = NSEvent.keyEvent(with: NSEvent.EventType.keyUp,
                     location: NSPoint(),
                     modifierFlags: NSEvent.ModifierFlags.command,
                     timestamp: TimeInterval(),
                     windowNumber: 0,
                     context: NSGraphicsContext(),
                     characters: "",
                     charactersIgnoringModifiers: "",
                     isARepeat: false, 
                     keyCode: 0x0F);


    let cgEvent = customEvent!.cgEvent

    cgEvent!.postToPid(688) // I want to post to a process with pid 688

推荐答案

在您的情况下,您要做的就是在 CGEvent 实例上调用 postToPid 并传递PID作为参数:

In your case all you need to do is to call postToPid on your CGEvent instance, and pass the PID as argument:

let cgEvent = customEvent!.cgEvent
cgEvent?.postToPid(168) 

修改
您的代码不起作用,因为您只是发送一个按键事件,而不是CMD + R.您可以在AppleScript中轻松完成此操作.看到以下问题: Mac:在Chrome或Firefox中重新加载文档?

Edit
Your code doesn't work because you're just sending a key up event, not CMD+R. You can do this easily in AppleScript. See this question: Mac: reloading document in Chrome or Firefox?

编辑2

在没有AppleScript的情况下,这是我要这样做的方式:

Without AppleScript, this is how I would do it:

let src = CGEventSource(stateID: .hidSystemState)
if let event = CGEvent(keyboardEventSource: src, virtualKey: 0x0f, keyDown: true)
{
    event.flags = .maskCommand
    event.postToPid(your_browser_pid)
}

通过Safari成功测试.

Successfully tested with Safari.

这篇关于通过流程ID将KeyEvent发送到目标窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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