Send KeyEvent to a Target window via process Id

后端 未结 1 582
渐次进展
渐次进展 2021-01-27 08:17

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 custo         


        
相关标签:
1条回答
  • 2021-01-27 08:46

    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) 
    

    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?

    Edit 2

    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)
    }
    

    Successfully tested with Safari.

    0 讨论(0)
提交回复
热议问题