Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7963899
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T05:44:03+00:00 2026-06-04T05:44:03+00:00

I use the following code to listen to global key events: Win32HookManager.java import com.sun.jna.platform.win32.Kernel32;

  • 0

I use the following code to listen to global key events:

Win32HookManager.java

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


import java.awt.event.KeyEvent;

public class Win32HookManager {
    private static HHOOK keyboardHook;

    public static boolean installKeyboardHook(final NativeKeyboardListener listener) {
        final User32  lib  = User32.INSTANCE;
        final HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);

        final LowLevelKeyboardProc keyboardHookProc = new LowLevelKeyboardProc() {
            @Override
            public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
                NativeKeyboardEvent ev = null;
                long                ti = System.currentTimeMillis();
                boolean             nh = true;

                if (nCode >= 0) {
                    switch (wParam.intValue()) {
                        case WinUser.WM_KEYDOWN:
                        case WinUser.WM_SYSKEYDOWN:
                            ev = new NativeKeyboardEvent(KeyEvent.KEY_PRESSED, ti, 0, info.vkCode);
                            nh = listener.keyPressed(ev);
                            break;

                        case WinUser.WM_KEYUP:
                        case WinUser.WM_SYSKEYUP:
                            ev = new NativeKeyboardEvent(KeyEvent.KEY_RELEASED, ti, 0, info.vkCode);
                            nh = listener.keyReleased(ev);
                            break;
                    }
                }

                if(nh) {
                    return lib.CallNextHookEx(keyboardHook, nCode, wParam, info.getPointer());
                }
                return new LRESULT(1);
            }
        };

        new Thread() {
            @Override
            public void run() {
                keyboardHook = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHookProc, hMod, 0);
                msgLoop();
                lib.UnhookWindowsHookEx(keyboardHook);
            }
        }.start();

        return keyboardHook != null;
    }

    public static boolean uninstallKeyboardHook() {
        if(keyboardHook != null) {
            return User32.INSTANCE.UnhookWindowsHookEx(keyboardHook);
        }

        return false;
    }

    private static void msgLoop()
    {
        final User32 lib = User32.INSTANCE;

        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);
            }
        }
    }
}

NativeKeyboardListener

public interface NativeKeyboardListener {
    public boolean keyPressed (NativeKeyboardEvent e);
    public boolean keyReleased(NativeKeyboardEvent e);
}

NativeKeyboardEvent

public class NativeKeyboardEvent {
    private int  id;
    private int  keyCode;

    public NativeKeyboardEvent(int id, long when, int modifiers, int keyCode) {
        this.id        = id;
        this.keyCode   = keyCode;
    }

    public int getId() {
        return id;
    }

    public int getKeyCode() {
        return keyCode;
    }
}

Unfortunately, it doesn’t work as I expected, i.e. it detects when a key is pressed/released, but it cannot finish the thread started by installKeyboardHook() method because of GetMessage() in msgLoop method. Yes, I can stop listening to key events, but I cannot stop the thread. However, it seems that GetMessage() is needed in this code. Do you see any workaround for this problem?

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T05:44:05+00:00Added an answer on June 4, 2026 at 5:44 am

    As @SLaks suggests, you need some sort of flag to indicate whether or not the message loop should continue to run. You can then use PeekMessage (JNA Doc) which, like GetMessage, retrieves a message from the queue, but is not a blocking operation. Your message loop should then be changed to something like this:

    while (!shouldQuit) {
        while ((result = lib.PeekMessage(msg, null, 0, 0, 1)) != 0) {
            // ...
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I use the following code to listen for the key presses of 0 -
I use following code to receive a connection: socat TCP-LISTEN:4000,fork EXEC:./myscrpit I need to
I use following code: Create a retry policy, when error, retry after 1 second,
I use VS2010, C# to develop Silverlight 4 app, I use following code in
I have an array of objects, and i use following code to get in
I use the following code try to create an array of string vectors, I
I use the following code to layout network drives on a system. I want
I use the following code: Calendar calendar = new GregorianCalendar(0,0,0); calendar.set(Calendar.YEAR, 1942); calendar.set(Calendar.MONTH, 3);
I use the following code to allocate a Console for a WinForm application. The
I use the following code: - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSHTTPURLResponse *)response {

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.