3

For an exercise, I would like to develop an application in Java that can make calls to Windows API and register itself for notification on events like key press.

From researches done earlier, I understand that the specific Windows API suitable for my need is the SetWindowsHookEx function.

Some have suggested using JNI for this, and others JNA. For the scenario I have described, What are the pros and cons for using either JNI or JNA?

I need opinions on how best to approach solving this problem.

Please do note guys, that I am aware that C/C++ would be most suitable for what I am doing. But like I stated right from the beginning - I am doing this as an exercise, and thus I want to accomplish it using Java.


This question is not a duplicate of Calling Win32 API method from Java, for the following reasons:

  • My question asks, what are the pros and cons of using JNI or JNA.
  • The other questions asks
    how to call an already existing DLL from Java

They are just not the same questions.

4

1 回答 1

4

For general-purpose invocation of native code, JNA tends to be much easier, because you don't have to write a C/C++ stub.

However, it's not always possible to do what you need via JNA. Let me explain why:

I think that for what you want to do, JNI is going to be required. The issue is that SetWindowsHookEx takes parameters including a pointer to the hook procedure and a handle to the DLL that contains the hook procedure. Windows will be using that info to invoke the hook procedure. As you might imagine, Windows is not going to be able call directly into a method of an object in the JVM.

So, I believe that you're going to have to use JNI to write a dll that will sit between your java app and the Windows API. That dll will contain the actual hook process, and will invoke SetWindowsHookEx for you. The dll's hook process can then use JNI to invoke your java object.

于 2013-01-15T22:10:07.737 回答