I am working with code( C++, ubuntu, gdk, xkb) where I use a german Keyboard which is on the top of the list in settings->Keyboard->input sources .
In my program I can access the keycode, keyval, keymaps used for the language which is on top of that list; (if I change the language I get different results – which is fine and of course should work this way)
Now in my C++ program I want to access the name of the active keyboard like "german" or "french". How can I access the name of the active keyboard using c++ gdk or xkb
2
Answers
To access the name of the active keyboard layout using C++ with GDK or XKB, you can use the following approaches:
Using GDK:
Get the current GdkSeat: Use the
gdk_display_get_default_seat()
function to retrieve the default GdkSeat associated with the display.Get the active GdkKeyboard: Use the
gdk_seat_get_keyboard()
function to obtain the active GdkKeyboard for the seat.Get the GdkKeymap: Use the
gdk_keyboard_get_keymap()
function to retrieve the GdkKeymap associated with the GdkKeyboard.Get the active layout name: Use the
gdk_keymap_get_layout_name()
function to obtain the name of the active keyboard layout.Here’s an example code snippet that demonstrates this approach:
Using XKB:
Open the connection to the X server: Use the
XOpenDisplay()
function to open a connection to the X server.Get the active XkbStateRec: Use the
XkbGetState()
function to retrieve the current XkbStateRec structure.Get the XkbDescPtr: Use the
XkbGetKeyboard()
function to obtain the XkbDescPtr structure.Get the active layout name: Access the
names
field of the XkbDescRec structure to retrieve the name of the active keyboard layout.Here’s an example code snippet that demonstrates this approach:
Make sure to link against the appropriate GDK or XKB libraries when compiling your code.
Note: The GDK approach relies on the GDK library, which is a higher-level abstraction that sits on top of XKB. The XKB approach directly interacts with the XKB extension. Both approaches should give you the desired result, but you may choose the one that best fits your needs and existing codebase.
For Ubuntu, you can read it from /etc/default/keyboard:
Or use the setxkbmap command: