A JNativeHook example in Scala
I’ve been working on a few applications where I want to get access to native, global keystrokes and mouse movements, so I’ve been using the JNativeHook library, which seems to work well on Mac OS X systems. I’ve been using Scala for all my coding the last few years instead of Java, so here’s a quick Scala port of the JNativeHook GlobalMouseListenerExample:
package jnativehookexample
import org.jnativehook.GlobalScreen
import org.jnativehook.NativeHookException
import org.jnativehook.mouse.NativeMouseEvent
import org.jnativehook.mouse.NativeMouseInputListener
class GlobalMouseListenerExample extends NativeMouseInputListener {
def nativeMouseClicked(e: NativeMouseEvent) {
println(s"Mouse Clicked: ${e.getClickCount}")
}
def nativeMousePressed(e: NativeMouseEvent) {
println(s"Mouse Pressed: ${e.getButton}")
}
def nativeMouseReleased(e: NativeMouseEvent) {
println(s"Mouse Released: ${e.getButton}")
}
def nativeMouseMoved(e: NativeMouseEvent) {
println(s"Mouse Moved: ${e.getX}, ${e.getY}")
}
def nativeMouseDragged(e: NativeMouseEvent) {
println(s"Mouse Dragged: ${e.getX}, ${e.getY}")
}
}
object GlobalMouseListenerExample extends App {
try {
GlobalScreen.registerNativeHook
} catch {
case ex: NativeHookException =>
System.err.println("There was a problem registering the native hook.")
System.err.println(ex.getMessage)
System.exit(1)
}
//construct the example object
val example = new GlobalMouseListenerExample
//add the appropriate listeners for the example object
GlobalScreen.getInstance.addNativeMouseListener(example)
GlobalScreen.getInstance.addNativeMouseMotionListener(example)
}
I just realized that I didn’t change the println statements initially, so I just updated those to use string interpolation. If I didn’t make any mistakes in changing those, the rest of the code should work fine. To run the example you’ll need to use the JNativeHook library and its dependencies.
Note: For your application to work properly on Mac OS X systems, you need to enable “access for assistive devices” for your application. On Mac OS X 10.9, that setting is under System Preferences > Security & Privacy > Privacy tab > Accessibility > Your Application.
Recent blog posts
- Business Analyst: How to write accurate software requirements
- Business Analyst: A simple secret to running a great meeting
- One thing a business analyst should ask about any requirement
- Business Analysts and Use Case quality: Questions to ask yourself when writing a Use Case
- The three things a Business Analyst should think about during meetings
- Testing web applications Selenium with Scala 3 and ScalaTest
- Scala Cookbook 2021: A best-selling new release in OOP and FP
- Salar Rahmanian's newsletter (and Functional Programming, Simplified)
- Our “Back To Now” app: Now available on iOS and Android
- An Android location “Fused Location Provider API” example