使用java屏蔽Esc,Ctrl,F1-12等按键

用到jna-4.2.2.jar和jna-platform-4.2.2.jar

package com.xxx.proj.browser;

import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HMODULE;
import com.sun.jna.platform.win32.WinDef.LRESULT;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import com.sun.jna.platform.win32.WinUser;

public class KeyboardHook implements Runnable {
	private WinUser.HHOOK hhk;
	// 钩子回调函数
	private WinUser.LowLevelKeyboardProc keyboardProc = new WinUser.LowLevelKeyboardProc() {

		@Override
		public LRESULT callback(int nCode, WPARAM wParam, WinUser.KBDLLHOOKSTRUCT event) {
			if (nCode >= 0) {
				System.out.println("nCode:" + wParam + ", KEY: " + event.vkCode);
				// 屏蔽windows,alt,tab,del键
				switch (event.vkCode) {
				case 27:// esc
					if (wParam.intValue() == 256) {
						BrowserDialog browser = SwingBrowser.browser;
						PasswordDialog password = SwingBrowser.password;
						// 如果密码框存在,销毁密码框显示考试窗
						if (browser != null) {
							if (password.isVisible()) {
								password.setVisible(false);
								browser.setAlwaysOnTop(true);
							} else {
								browser.setAlwaysOnTop(false);
								password.setAlwaysOnTop(true);
								password.setVisible(true);
							}
						}
					}
				case 91: // windows
				case 162:// ctl
				case 164:// alt
				case 9:// tab
				case 115:// f4
				case 116:// f5
				case 123:// f12
				case 46:// del
					return new LRESULT(1);
				}
			}
			return User32.INSTANCE.CallNextHookEx(hhk, nCode, wParam, null);
		}

	};

	public void run() {
		System.out.println("Hook On!");
		HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
		hhk = User32.INSTANCE.SetWindowsHookEx(User32.WH_KEYBOARD_LL, keyboardProc, hMod, 0);
		int result;
		WinUser.MSG msg = new WinUser.MSG();
		while ((result = User32.INSTANCE.GetMessage(msg, null, 0, 0)) != 0) {
			System.out.println(System.currentTimeMillis() + "!");
			if (result == -1) {
			} else {
				User32.INSTANCE.TranslateMessage(msg);
				User32.INSTANCE.DispatchMessage(msg);
			}
		}
	}

	public static void main(String[] args) {
		KeyboardHook kbhook = new KeyboardHook();
		new Thread(kbhook).start();
	}
}

源码:https://download.csdn.net/download/aidy2008/10678219

你可能感兴趣的:(jna)