Java原生API並不支援為應用程式設定全域熱鍵。要實現全域熱鍵,需要用JNI方式實現,這涉及到編寫C/C++程式碼,這對於大多數不熟悉C/C++的javaer來說,有點困難。不過幸好,國外有人已經實現了,發布成第三方java包,藉此,我們可以很方便的設定全域熱鍵而不用寫任何C/C++程式碼。
jintellitype官網似乎無法存取,這裡提供下載://www.VeVB.COm/softs/217788.html。
jintellitype由兩個部分組成,一部分是java寫的jintellityp的jar文件,另一部分是C/C++寫的已編譯好的dll文件,有兩個dll文件,分別是32位元和64位元系統的。在我使用jintellitype的過程中,把jintellitype的jar檔案Build進專案後,不知道dll檔案放哪,我試著運行,根據錯誤提示,原來需要把dll檔案放到專案com.melloware.jintellitype包下。建議同時把兩個dll檔案都加進去,這樣,你的程式就可以同時相容32位元和64位元系統,而你不需要任何額外的處理。
貼上我的小demo程式碼:
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.JFrameFrame import javax. .JOptionPane; import com.melloware.jintellitype.HotkeyListener; import com.melloware.jintellitype.JIntellitype; /** * 利用JIntellitype實作全域熱鍵設定* @author Jeby Sun * */ public class GlobleHotKeyDemo extends JFrame { private statsion finalIDDemo extends //定義熱鍵標識,用於在設定多個熱鍵時,在事件處理中區分使用者按下的熱鍵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); }); (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() {oid @Overtype.getInstance().addHotKeyListener(new HotkeyListener() {oid @Overtype.getInstance().addHotKeyListener(new HotkeyListener() {oid @Override public void @Override 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檔案;
第二步:註冊熱鍵;
第三步:新增熱鍵監聽器,實現介面的方法;