jna介绍

曾今写过jni包装unrar, http://blog.ureshika.com/archives/391.html

感觉jni用起来很麻烦,现在发现有了jna,很好很强大!

官网: https://github.com/twall/jna

需要下载jna.jar和platform.jar两个包。

下面是全局键盘钩子并获取剪贴板内容的例子:

package kzg.jna;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import com.sun.jna.platform.win32.*;
import com.sun.jna.platform.win32.WinUser.*;
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.HHOOK;
import com.sun.jna.platform.win32.WinUser.KBDLLHOOKSTRUCT;
import com.sun.jna.platform.win32.WinUser.LowLevelKeyboardProc;

public class KeyHookTest {
	private static boolean quit;
	private static HHOOK hhk;
	private static LowLevelKeyboardProc keyboardHook;

	public static void main(String[] args) {
		final User32 lib = User32.INSTANCE;
		HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
		keyboardHook = new LowLevelKeyboardProc() {

			@Override
			public LRESULT callback(int nCode, WPARAM wParam,
					KBDLLHOOKSTRUCT info) {
				if (nCode >= 0) {
					if (info.vkCode == 81) {
						quit = true;
					}
					Clipboard clip = Toolkit.getDefaultToolkit()
							.getSystemClipboard();
					Transferable clipT = clip.getContents(null);
					if (clipT != null) {
						if (clipT
								.isDataFlavorSupported(DataFlavor.stringFlavor)) {

							try {
								String cliptxt = (String) clipT.getTransferData(DataFlavor.stringFlavor);
								System.out.println("got clipborad text:" + cliptxt);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}
				return lib
						.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
			}
		};
		hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod,
				0);
		System.out
				.println("Keyboard hook installed, type anywhere, 'q' to quit");
		new Thread() {
			public void run() {
				while (!quit) {
					try {
						Thread.sleep(10);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				System.err.println("unhook and exit");
				lib.UnhookWindowsHookEx(hhk);
				System.exit(0);
			}
		}.start();

		int result;
		MSG msg = new MSG();
		while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
			if (result == -1) {
				System.err.println("error in get message");
				break;
			} else {
				System.err.println("got message");
				lib.TranslateMessage(msg);
				lib.DispatchMessage(msg);
			}
		}
		lib.UnhookWindowsHookEx(hhk);
	}
}

参见:

http://blog.csdn.net/shendl/article/details/3589676

http://www.iteye.com/problems/19087


Total views.

© 2013 - 2024. All rights reserved.

Powered by Hydejack v6.6.1