首页 文章

是否可以将密钥代码发送到不在前面的应用程序?

提问于
浏览
0

我正在用Javascript编写一个简单的Automator脚本 .

我想将密钥代码(或密钥存储)发送到不在前面的OS X应用程序 .

基本上,我想运行这段代码并在脚本打开某个应用程序,写入文本和点击输入时执行我的操作 - 所有这一切都没有打扰我的其他工作 .

我想要这样的东西: Application("System Events").processes['someApp'].windows[0].textFields[0].keyCode(76);

在“脚本字典”中, Processes Suite 下有 keyCode 方法 . 但是,上面的代码会引发一个错误: execution error: Error on line 16: Error: Named parameters must be passed as an object. (-2700)

我知道以下代码工作正常,但它需要应用程序在前面运行: // KeyCode 76 => "Enter" Application("System Events").keyCode(76);

UPDATE :我正在尝试在iTunes(Apple Music)上搜索某些内容 . 如果没有预先提供iTunes应用程序,这可能吗?

1 回答

  • 1

    GUI Scriptingaccessibility )的帮助下,可以在应用程序中写入文本,但是:

    • 您需要知道特定应用程序窗口中的UI元素,并了解特定元素的属性和属性 .

    • 您需要在 System Preferences --> Security & Privacy --> Accessibility 中添加脚本 .


    这是一个示例脚本(在 macOS Sierra 上测试),用于在“ TextEdit ”应用程序的前端文档中的光标位置写入一些文本 .

    Application("System Events").processes['TextEdit'].windows[0].scrollAreas[0].textAreas[0].attributes["AXSelectedText"].value = "some text" + "\r" // r is the return KEY
    

    Update

    要将一些关键代码发送到后台应用程序,可以使用 Carbon 框架的 CGEventPostToPid() 方法 .

    这是在iTunes中搜索某些文本的脚本(在我的计算机上运行, macOS SierraiTunes Version 10.6.2 ) .

    ObjC.import('Carbon')
    iPid = Application("System Events").processes['iTunes'].unixId()
    searchField = Application("System Events").processes['iTunes'].windows[0].textFields[0]
    searchField.buttons[0].actions['AXPress'].perform()
    delay(0.1) // increase it, if no search 
    searchField.focused = true
    delay(0.3) // increase it, if no search 
    searchField.value = "world" // the searching text
    searchField.actions["AXConfirm"].perform()
    delay(0.1) // increase it, if no search 
    
    // ** carbon methods to send the enter key to a background application ***
    enterDown = $.CGEventCreateKeyboardEvent($(), 76, true);
    enterUp = $.CGEventCreateKeyboardEvent($(), 76, false);
    $.CGEventPostToPid(iPid, enterDown);
    delay(0.1)
    $.CGEventPostToPid(iPid, enterUp);
    

相关问题