Java原生API并不支持為應用程序設置全局熱鍵。要實現全局熱鍵,需要用JNI方式實現,這就涉及到編寫C/C++代碼,這對于大多數不熟悉C/C++的javaer來說,有點困難。不過幸好,國外有人已經實現了,發布成第三方java包,借此,我們可以很方便的設置全局熱鍵而不用編寫任何C/C++代碼。
jintellitype官網貌似目前訪問不到。
jintellitype由兩部分組成,一部分是java寫的jintellityp的jar文件,另一部分是C/C++寫的已編譯好的dll文件,有兩個dll文件,分別是32位和64位系統的。在我使用jintellitype的過程中,把jintellitype的jar文件Build進項目后,不知道dll文件放哪,我試著運行,根據錯誤提示,原來需要把dll文件放到項目com.melloware.jintellitype包下。建議同時把兩個dll文件都加進去,這樣,你的程序就可以同時兼容32位和64位系統,而你不需要任何額外的處理。
貼上我的小demo代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
package com.jebysun.globlehotkey; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import com.melloware.jintellitype.HotkeyListener; import com.melloware.jintellitype.JIntellitype; /** * 利用JIntellitype實現全局熱鍵設置 * @author Jeby Sun * */ public class GlobleHotKeyDemo extends JFrame { private static final long serialVersionUID = 1L; //定義熱鍵標識,用于在設置多個熱鍵時,在事件處理中區分用戶按下的熱鍵 public static final int FUNC_KEY_MARK = 1 ; public static final int EXIT_KEY_MARK = 0 ; JButton msgBtn; JButton exitBtn; public GlobleHotKeyDemo() { this .setTitle( "全局熱鍵設置" ); this .setBounds( 100 , 100 , 600 , 400 ); this .setLayout( null ); this .setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); msgBtn = new JButton( "彈出框(Alt+S)" ); //設置按鈕邊距 msgBtn.setMargin( new Insets( 0 , 0 , 0 , 0 )); msgBtn.setFocusable( false ); msgBtn.setBounds( 20 , 20 , 120 , 30 ); msgBtn.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showMessage(); } }); this .add(msgBtn); exitBtn = new JButton( "退出(Alt+Q)" ); exitBtn.setMargin( new Insets( 0 , 0 , 0 , 0 )); exitBtn.setFocusable( false ); exitBtn.setBounds( 160 , 20 , 120 , 30 ); exitBtn.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit( 0 ); } }); this .add(exitBtn); //第一步:注冊熱鍵,第一個參數表示該熱鍵的標識,第二個參數表示組合鍵,如果沒有則為0,第三個參數為定義的主要熱鍵 JIntellitype.getInstance().registerHotKey(FUNC_KEY_MARK, JIntellitype.MOD_ALT, ( int ) 'S' ); JIntellitype.getInstance().registerHotKey(EXIT_KEY_MARK, JIntellitype.MOD_ALT, ( int ) 'Q' ); //第二步:添加熱鍵監聽器 JIntellitype.getInstance().addHotKeyListener( new HotkeyListener() { @Override public void onHotKey( int markCode) { switch (markCode) { case FUNC_KEY_MARK: showMessage(); break ; case EXIT_KEY_MARK: System.exit( 0 ); break ; } } }); this .setVisible( true ); } public void showMessage() { JOptionPane.showMessageDialog( null , "就算把窗口最小化,按快捷鍵Alt+S也可以彈出提示框哦!" , "彈出框標題" , JOptionPane.INFORMATION_MESSAGE); } public static void main(String[] args) { new GlobleHotKeyDemo(); } } |
其實,jintellitype的使用非常簡單,就3個步驟:
第一步:添加jar包和dll文件;
第二步:注冊熱鍵;
第三步:添加熱鍵監聽器,實現接口的方法;