2

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();
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
stove
  • 556
  • 6
  • 24

2 Answers2

1

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

  • GetKeyboardLayout : will give a DWORD whose lower word identifies language and sublanguage -> to use if you just switch between a limited an known list of layouts
  • GetKeyboardLayoutName : will (almost) directly give you a null terminated string - extract from documentation :

    Syntax

    BOOL GetKeyboardLayoutName(LPTSTR pwszKLID);
    

    Parameters

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 ...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • this helped me along with the answer here: http://stackoverflow.com/questions/12379713/cant-get-current-keyboard-layout thanks! – stove Feb 04 '15 at 12:24
0

You can use JNA for this:

import com.sun.jna.platform.win32.User32
import com.sun.jna.platform.win32.WinDef

val layout: WinDef.HKL = User32.INSTANCE.GetKeyboardLayout(0)

Gradle:

 implementation("net.java.dev.jna:jna-platform:5.12.1")