Java原生API并不支持为应用程序设置全局热键。要实现全局热键,需要用JNI方式实现,这就涉及到编写C/C++代码,这对于大多数不熟悉C/C++的javaer来说,有点困难。不过幸好,国外有人已经实现了,发布成第三方java包,借此,我们可以很方便的设置全局热键而不用编写任何C/C++代码。
jintellitype官网貌似目前访问不到,这里提供下载:http://pan.baidu.com/s/1kTIDxgN。
jintellitype由两部分组成,一部分是java写的jintellityp的jar文件,另一部分是C/C++写的已编译好的dll文件,有两个dll文件,分别是32位和64位系统的。在我使用jintellitype的过程中,把jintellitype的jar文件Build进项目后,不知道dll文件放哪,我试着运行,根据错误提示,原来需要把dll文件放到项目com.melloware.jintellitype包下。建议同时把两个dll文件都加进去,这样,你的程序就可以同时兼容32位和64位系统,而你不需要任何额外的处理。
贴上我的小demo代码:
1 packagecom.jebysun.globlehotkey;2
3 importjava.awt.Insets;4 importjava.awt.event.ActionEvent;5 importjava.awt.event.ActionListener;6
7 importjavax.swing.JButton;8 importjavax.swing.JFrame;9 importjavax.swing.JOptionPane;10
11 importcom.melloware.jintellitype.HotkeyListener;12 importcom.melloware.jintellitype.JIntellitype;13
14 /**
15 * 利用JIntellitype实现全局热键设置16 *@authorJeby Sun17 *18 */
19 public class GlobleHotKeyDemo extendsJFrame {20
21 private static final long serialVersionUID = 1L;22
23 //定义热键标识,用于在设置多个热键时,在事件处理中区分用户按下的热键
24 public static final int FUNC_KEY_MARK = 1;25 public static final int EXIT_KEY_MARK = 0;26
27 JButton msgBtn;28 JButton exitBtn;29
30 publicGlobleHotKeyDemo() {31 this.setTitle("全局热键设置");32 this.setBounds(100, 100, 600, 400);33 this.setLayout(null);34 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);35
36 msgBtn = new JButton("弹出框(Alt+S)");37 //设置按钮边距
38 msgBtn.setMargin(new Insets(0,0,0,0));39 msgBtn.setFocusable(false);40 msgBtn.setBounds(20, 20, 120, 30);41 msgBtn.addActionListener(newActionListener() {42 @Override43 public voidactionPerformed(ActionEvent e) {44 showMessage();45 }46 });47 this.add(msgBtn);48
49 exitBtn = new JButton("退出(Alt+Q)");50 exitBtn.setMargin(new Insets(0,0,0,0));51 exitBtn.setFocusable(false);52 exitBtn.setBounds(160, 20, 120, 30);53 exitBtn.addActionListener(newActionListener() {54 @Override55 public voidactionPerformed(ActionEvent e) {56 System.exit(0);57 }58 });59 this.add(exitBtn);60
61 //第一步:注册热键,第一个参数表示该热键的标识,第二个参数表示组合键,如果没有则为0,第三个参数为定义的主要热键
62 JIntellitype.getInstance().registerHotKey(FUNC_KEY_MARK, JIntellitype.MOD_ALT, (int)'S');63 JIntellitype.getInstance().registerHotKey(EXIT_KEY_MARK, JIntellitype.MOD_ALT, (int)'Q');64
65 //第二步:添加热键监听器
66 JIntellitype.getInstance().addHotKeyListener(newHotkeyListener() {67
68 @Override69 public void onHotKey(intmarkCode) {70 switch(markCode) {71 caseFUNC_KEY_MARK:72 showMessage();73 break;74 caseEXIT_KEY_MARK:75 System.exit(0);76 break;77 }78 }79 });80
81 this.setVisible(true);82 }83
84 public voidshowMessage() {85 JOptionPane.showMessageDialog(null, "就算把窗口最小化,按快捷键Alt+S也可以弹出提示框哦!", "弹出框标题", JOptionPane.INFORMATION_MESSAGE);86 }87
88
89
90 public static voidmain(String[] args) {91 newGlobleHotKeyDemo();92 }93 }
其实,jintellitype的使用非常简单,就3个步骤:
第一步:添加jar包和dll文件;
第二步:注册热键;
第三步:添加热键监听器,实现接口的方法;