javawindowslocalekeyboard-layout

get current windows keyboard layout in Java


On windows I want to get the code I see in language bar on windows. I need to get this current keyboard layout at any given time.

If I use this in a thread:

InputContext is = InputContext.getInstance();
System.out.println(is.getLocale());

I'll get layout that was active when the program was started. But when i press either win+spacebar or alt+shift and change layout to something else, the thread will keep outputting previous language.

I didn't find any parameter that would reflex on keyboard layout in system properties either.

Thread example:

    Thread t = new Thread() {

        @Override
        public void run() {
            while(true) {
                InputContext is = InputContext.getInstance();
                System.out.println(is.getLocale());

                Properties p = System.getProperties();
                System.out.println(System.getProperty("user.language"));
                try {
                    sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(InputContextTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    };

    t.run();

Solution

  • AFAIK you will have to write some JNI to get it. There are 2 functions of interest in Windows API :

    pwszKLID [out] Pointer to the buffer (of at least KL_NAMELENGTH characters in length) that receives the name of the input locale identifier, including the terminating null character ...