kwhat / jnativehook

Global keyboard and mouse listeners for Java.
Other
1.73k stars 344 forks source link

EXCEPTION_ACCESS_VIOLATION (0xc0000005) #415

Open RFMFF opened 2 years ago

RFMFF commented 2 years ago

I have a very simple bit of code that is trying to call the postNativeEvent:

import com.github.kwhat.jnativehook.GlobalScreen;
import com.github.kwhat.jnativehook.NativeInputEvent;

public class TestGlobalScreen {
    public static void main (String[] args) {
        GlobalScreen.postNativeEvent(new NativeInputEvent(GlobalScreen.class, 2402, 0));
    }
}

When I execute, I get:

A fatal error has been detected by the Java Runtime Environment: EXCEPTION_ACCESS_VIOLATION (0xc0000005)

Can someone provide some light on what am I doing wrong? Running this in win10.

kwhat commented 2 years ago

This shouldn't crash if you send a NativeInputEvent but you shouldn't be sending a NativeInputEvent to postNativeEvent() because NativeInputEvent isn't suitable for producing an event on its own. When you pass it to postNativeEvent() with an id of 2402, you are telling the native code that NativeInputEvent is a NATIVE_KEY_RELEASED event but its not a NativeKeyEvent and does not have a getKeyCode() method to call so it crashes.

There are two possible resolutions to this bug:

  1. Make NativeInputEvent abstract to prevent construction.
  2. Add a type check to Java_com_github_kwhat_jnativehook_GlobalScreen_postNativeEvent() NativeInputEvent_obj instead of running a switch against the event id.

I am pretty sure we will have to do the second one:

if ((*env)->IsInstanceOf(env, NativeInputEvent_obj, com_github_kwhat_jnativehook_keyboard_NativeKeyEvent->cls)) {
    ...
} else if ((*env)->IsInstanceOf(env, NativeInputEvent_obj, com_github_kwhat_jnativehook_mouse_NativeMouseEvent->cls)) {
    ...
}