本文使用melloware的JIntellitype,操作前先下载jar包支持和动态链接库(github地址:https://github.com/melloware/jintellitype)
demo代码:
package createglobalhotkey;
import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.IntellitypeListener;
import com.melloware.jintellitype.JIntellitype;
import java.util.Scanner;
public class TestMethod {
public static void main(String[] args) {
JIntellitype.getInstance().registerHotKey(1, JIntellitype.MOD_CONTROL,66);//k
System.out.println("热键注册成功!你可以使用了!");
JIntellitype.getInstance().addHotKeyListener(new HotkeyListener() {
public void onHotKey(int markCode) {
if (markCode==1){
System.out.println("ctl+b 起作用了...");
}
}
});
System.out.println("要取消热键,请输入1:");
Scanner sc=new Scanner(System.in);
int i = sc.nextInt();
if (i==1) {
HotKeyThread hotKeyThread=new HotKeyThread();
hotKeyThread.start();
}
}
}
调用线程取消热键的类:
package createglobalhotkey;
import com.melloware.jintellitype.JIntellitype;
public class HotKeyThread extends Thread {
@Override
public void run(){
JIntellitype.getInstance().unregisterHotKey(1);
System.out.println("热键已取消!");
JIntellitype.getInstance().cleanUp();
}
}
一,JIntellitype调用getInstance()方法后有两个重构方法registerHotKey()注册热键,分别为:
1.registerHotKey(int identifier, int modifier, int keycode)
2.registerHotKey(int identifier, String modifierAndKeyCode)
其中:
identifier为自定义的热键的标识
modifier为键shift/win/ctrl/alt一个或多个的值(整型,JIntellitype静态成员已定义),取值见JIntellitype.swingToIntelliType()方法,如果不要组合键,参数为0
keycode为键盘码,可由JIntellitype.getKey2KeycodeMapping()方法中查看
modifierAndKeyCode为键shift/win/ctrl/alt一个或多个的字符串值(字符串类型,大写)
二,JIntellitype调用getInstance()方法后调用[热键]addHotKeyListener()或者[媒体类型]addIntellitypeListener()监听,方法参数为类HotkeyListener或IntellitypeListener的对象,可通过匿名内部类重写处理方法
三,释放热键参见demo的HotKeyThread线程类中实现