从java运行autohotkey(ahk)脚本

时间:2013-09-14 21:11:50

标签: java windows autohotkey

有没有办法用java中的参数运行脚本? 不是可执行文件,而是AutoHotKey脚本。

我尝试了这个,但由于它不是有效的可执行文件,因此不起作用。

控制类:

package org.bsep.acp;

import java.io.IOException;

/**
 * This class allow you to send string to your
 * computer as keystrokes.
 * 
 * escape car is '
 * special char are {space}, {Enter}, {F1}, {F2}, etc
 * 
 * @author Eildosa
 */
public class StringSender {

    Runtime runtime;
    private final static String AHK_BRIDGE = "C:\\perso\\WorkspaceScripts\\skyrimTools\\src\\org\\bsep\\acp\\ahkBridge.ahk";

    public StringSender() {
        runtime = Runtime.getRuntime();
    }

    public void sendString(String data) throws IOException, InterruptedException {
        runtime.exec(new String[] { AHK_BRIDGE, data} );
        Thread.currentThread();
        Thread.sleep(1000);
    }

}

测试:

Runtime runtime = Runtime.getRuntime();
runtime.exec(NOTEPAD);
Thread.currentThread();
Thread.sleep(4000);
StringSender stringSender = new StringSender();
stringSender.sendString("Writing from java through AHK.");

例外:

Exception in thread "main" java.io.IOException: Cannot run program "C:\perso\WorkspaceScripts\skyrimTools\src\org\bsep\acp\ahkBridge.ahk": CreateProcess error=193, %1 n?est pas une application Win32 valid
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
    at java.lang.Runtime.exec(Runtime.java:617)
    at java.lang.Runtime.exec(Runtime.java:485)
    at org.bsep.acp.StringSender.sendString(StringSender.java:25)
    at org.bsep.acp.VariousTests.ahkBridgeTester(VariousTests.java:23)
    at org.bsep.acp.VariousTests.main(VariousTests.java:13)
Caused by: java.io.IOException: CreateProcess error=193, %1 n?est pas une application Win32 valid
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:376)
    at java.lang.ProcessImpl.start(ProcessImpl.java:136)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1022)
    ... 5 more

翻译:这不是一个有效的win32应用程序。

感谢。

2 个答案:

答案 0 :(得分:6)

由于原始AHK脚本不可执行,您可以编译脚本并直接执行它,也可以将脚本路径作为参数传递给AutoHotkey.exe(通常位于C:\Program Files\AutoHotkey\)。关于第二个选项,您的代码可能如下所示:

public void sendString(String data) throws IOException, InterruptedException {
    String ahkPath = "C:\\Program Files\\AutoHotkey\\AutoHotkey.exe";
    String scriptPath = "C:\\Users\\MCL\\test.ahk";
    runtime.exec(new String[] { ahkPath, scriptPath, data} );
    Thread.currentThread();
    Thread.sleep(1000);
}

AutoHotkey会将每个参数传递给脚本,从第二个开始(在这种情况下:data)。

答案 1 :(得分:0)

你可以把另一个中间人带入其中,即启动ahk的蝙蝠脚本。哪个可以通过exec启动,这是一个关于启动bat的帖子

How do I run a batch file from my Java Application?

首先尝试命令行调用ahk传递脚本,但我不确定是否会有效,值得一试