Skip to content

Instantly share code, notes, and snippets.

@Infocatcher
Last active August 29, 2015 14:14
Show Gist options
  • Save Infocatcher/6b8627834570a0892423 to your computer and use it in GitHub Desktop.
Save Infocatcher/6b8627834570a0892423 to your computer and use it in GitHub Desktop.
Get keyboard layout on Gecko-based browsers, Windows-only
// Based on code from TabLang extension: https://addons.mozilla.org/addon/tablang/
// and Master Password+ extension https://addons.mozilla.org/addon/master-password/
var kb = {
GetKeyboardLayout: null,
GetLocaleInfoW: null,
init: function()
{
this.init = function() {};
Components.utils.import("resource://gre/modules/ctypes.jsm", this);
let ctypes = this.ctypes;
let a = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
let abi = a.XPCOMABI.indexOf("x86_64") == -1 ? ctypes.winapi_abi : ctypes.default_abi;
this.GetKeyboardLayout = ctypes.open("user32.dll").declare("GetKeyboardLayout", abi, ctypes.uintptr_t, ctypes.uint32_t);
this.GetLocaleInfoW = ctypes.open("kernel32.dll").declare("GetLocaleInfoW", abi, ctypes.int32_t, ctypes.uint32_t, ctypes.uint32_t, ctypes.jschar.ptr, ctypes.int32_t);
},
getLangNameAbr: function()
{
this.init();
try
{
let ctypes = this.ctypes;
let lcid = ctypes.UInt64.lo(ctypes.UInt64("0x" + this.GetKeyboardLayout(0).toString(16))) & 0xFFFF;
let bufferLength = this.GetLocaleInfoW(lcid, 89, ctypes.jschar.ptr(0), 0);
if (bufferLength == 0)
return;
let buffer = ctypes.jschar.array(bufferLength)();
if (this.GetLocaleInfoW(lcid, 89, ctypes.cast(buffer.address(), ctypes.jschar.ptr), bufferLength) != 0)
return buffer.readString();
}
catch(e){};
}
};
alert(kb.getLangNameAbr());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment