我正在编写一个将持续运行的程序,我想知道是否存在与Autoit SetHotKey(Key,Action())等效的Java。我在这里看到了一个与GUI界面相关的答案,但我的程序没有GUI。我只是希望程序在按下某个键时退出,最好是ESC。
我使用awt.Robot的keyevents在无限循环中运行程序,我希望能够通过按某个键退出程序。
答案 0 :(得分:2)
没有核心Java解决方案,因为Java被构建为尽可能与操作系统无关,为了实现您的目标,您需要一个可以更接近操作系统集成的程序。我所知道的主要解决方案是通过JNA,JNI或(我最喜欢的)AutoIt将您的程序集成到操作系统。通过简单地让我的Java程序和AutoIt通过标准IO和套接字进行通信来做类似的事情。
一个简单的例子:
Java程序,TrialAutoIt3a.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class TrialAutoIt3a {
// ***** of course your path to program will be different
private static final String AUTOIT_PATH = "C:/Users/Pete/Documents/Programming/AutoIt/Experiment/";
private static final String AUTOIT_EXEC = "TestWithJava.exe";
protected static final CharSequence EXIT = "exit";
private static Process proc = null;
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.println("Type \"exit\" to exit program");
try {
proc = rt.exec(AUTOIT_PATH + AUTOIT_EXEC);
} catch (IOException e1) {
e1.printStackTrace();
System.exit(-1);
}
InputStream iStream = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(iStream);
final BufferedReader bufReader = new BufferedReader(isr);
OutputStream oStream = proc.getOutputStream();
final PrintWriter pw = new PrintWriter(oStream, true);
Runnable bufReaderRunnable = new Runnable() {
public void run() {
String output;
try {
while ((output = bufReader.readLine()) != null) {
System.out.println(output);
if (output.toLowerCase().contains(EXIT)) {
proc.destroy();
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufReader != null) {
try {
bufReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
new Thread(bufReaderRunnable).start();
Runnable myRun = new Runnable() {
public void run() {
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
String line = scan.nextLine();
pw.println(line);
}
scan.close();
}
};
new Thread(myRun).start();
}
}
AutoIt程序,TestWithJava.au3:
Local $line = ""
While (True)
$line = $line & ConsoleRead()
If StringInStr($line, @CR) Or StringInStr($line, @LF) Then
ConsoleWrite($line & "to java" & @CRLF)
$line = ""
EndIf
Sleep(25)
WEnd
在运行此程序之前,AutoIt程序将被编译为exe文件