October 22, 2024
Chicago 12, Melborne City, USA
java

How to get an operating system's internal/keyboard charset, related to alt-key character input


Preface

I’m currently working on a small app that

  • literally types the input
  • from the system Clipboard (using Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);),
  • by simulating the keystrokes of the keyboard (using java.awt.Robot.keyPress(keyCode)).

This is for some instances where UI elements do not support copy-paste (neither ctrl+v nor shift+ins), or deadkey control is blocked in the app or on the whole system.

It took me quite a while to find a simple solution: use the Alt-Key input method. (Essentially press Alt, enter the code, for example 0128 for , then release Alt, badaa: you get .

To get that code, I can simlpy convert the char to bytes (String.getBytes and new String(bytes)), but for both methods I need to specify the proper charset, because Java will try to use UTF-8, which is wrong there.

This all works perfectly fine for all occasions I have encountered so far.

Problem

BUT: this method has one downside: I need to know the Operating System’s keyboard charset/codepage.

Usually, under windows, it is they single-byte CP1252, but this will vary across countries and operating systems.

Question:

How to find out which charset/codepage the current operating system is sporting for keyboard input?

(Preferred answer related to Java, if possible.)

Hints

The following ways to retrieve the charsets are NOT viable, as they’re only related to file I/O:

  • java.lang.System.getProperty("file.encoding")
  • java.nio.charset.Charset.defaultCharset()
  • java.io.FileReader.getEncoding() (which is just java.io.InputStreamReader.getEncoding() and usually just ends up calling java.nio.charset.Charset.defaultCharset() anyways…)
  • JVM’s command line parameter like java -Dfile.encoding=XXX app or client.encoding.override, but that would need to be adjusted manually, which is a task better not left to the user

I have found so far:

  • Windows PowerShell: [System.Text.Encoding]::Default, but that needs Windows and a PowerShell…
  • Do I have to go JNI and BOOL GetKeyboardLayoutName(LPTSTR pwszKLID); and hope I get this to match with Java’s Charsets?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video