Browse Source

Ading README, prevent multiple listener attachements, events on KeyUp.

Matt Clark 2 years ago
parent
commit
7dcc0f849c

+ 42 - 0
README.md

@@ -0,0 +1,42 @@
+# KeyHook
+
+A Java/Native global keyboard hook.
+
+## Usage
+
+Using the library is as simple as adding a Maven dependency and a few lines to handle the events.
+
+### Maven
+
+```
+<dependency>
+    <groupId>com.mclarkdev.tools</groupId>
+    <artifactId>KeyHook</artifactId>
+    <version>1.0</version>
+</dependency>
+```
+
+### Java
+
+Create an EventListener to handle the keyboard events.
+
+```
+private EventListener eventListener = new EventListener() {
+
+    @Override
+    public void onEvent(ArrayList<Integer> keyMap) {
+
+        String keys = keyMap.stream().map(Object::toString)//
+                .collect(Collectors.joining(", "));
+
+        System.out.println("Keys:" + keys);
+    }
+};
+```
+
+Attach the listener to the KeyboardManager.
+
+```
+KeyboardManager.getInstance().attachListener(eventListener);
+```
+

+ 5 - 1
src/main/java/com/mclarkdev/tools/KeyHook/KeyboardHook.java

@@ -25,7 +25,11 @@ public class KeyboardHook {
 		(new Thread(runThread)).start();
 	}
 
-	public void setListener(KeyListener listener) {
+	public void attachListener(KeyListener listener) {
+
+		if (this.listener != null) {
+			throw new IllegalArgumentException("listener already attached");
+		}
 
 		this.listener = listener;
 	}

+ 11 - 2
src/main/java/com/mclarkdev/tools/KeyHook/KeyboardManager.java

@@ -22,10 +22,14 @@ public class KeyboardManager {
 	private KeyboardManager() {
 
 		keysDown = new HashSet<>();
-		KeyboardHook.getInstance().setListener(keyListener);
+		KeyboardHook.getInstance().attachListener(keyListener);
 	}
 
-	public void setListener(EventListener listener) {
+	public void attachListener(EventListener listener) {
+
+		if (this.listener != null) {
+			throw new IllegalArgumentException("listener already attached");
+		}
 
 		this.listener = listener;
 	}
@@ -34,9 +38,14 @@ public class KeyboardManager {
 
 		public void onKeyUp(KBDLLHOOKSTRUCT event) {
 
+			ArrayList<Integer> keys;
 			synchronized (keysDown) {
+
 				keysDown.remove(Integer.valueOf(event.vkCode));
+				keys = new ArrayList<>(keysDown);
 			}
+
+			listener.onEvent(keys);
 		}
 
 		public void onKeyDown(KBDLLHOOKSTRUCT event) {