By Yariv Amar
Introduction. 1
Working with
windows API 1
Sample code. 1
Adding
functionality. 2
Retrieve current
keyboard layout name. 2
Changing the
keyboard layout 3
Building a winForm
driver 3
About the Author 4
I think that for
most of the non English-native users, Windows OS is installed with at least 2
languages. Changing the language manually is done using ALT+CTRL, but what if
you want to write a Win-Form that will select the language automatically? How
to select keyboard layout? Keep reading to find out.
Please read C# And API's article
num.79.
In this article I
will demonstrate how use:
Other resources
|
Identifier
|
Language
|
|
0x0000
|
Language Neutral
|
|
0x0409
|
English (United States)
|
|
0x040d
|
Hebrew
|
OK, now that we’ve
got the knowledge, let’s start working.
In this demo code
I will show how to create a LanguageSelector DLL.
- Create a new C# Class Library
project, name it LanguageSelector.
- add : using
System.Runtime.InteropServices;
- add the following constants:
const uint
KLF_ACTIVATE = 1; //activate the layout
const int KL_NAMELENGTH = 9; // length of the
keyboard buffer
const string
LANG_EN_US = "00000409";
const string
LANG_HE_IL = "0000040d";
- Next import the LoadKeyboardLayout
function from the “user32.dll”
[DllImport("user32.dll")]
private static
extern long
LoadKeyboardLayout(
string pwszKLID, // input locale identifier
uint Flags // input locale identifier options
);
- The same import for the GetKeyboardLayoutName:
[DllImport("user32.dll")]
private static
extern long
GetKeyboardLayoutName(
System.Text.StringBuilder
pwszKLID //[out] string that receives the name of the locale
identifier
);
- Please notice the StringBuilder
– one could use [MarshelAs…] property instead of the StringBuilder. For
the simplicity of the code and not dealing with Managed / Unmanaged code,
I didn’t use the marshaling system.
The code below warps the GetKeyboardLayoutName DLL function into more convenient method, easy to use later on.
public static string
getName()
{
System.Text.StringBuilder
name = new
System.Text.StringBuilder(KL_NAMELENGTH);
GetKeyboardLayoutName(name);
return name.ToString();
}
Tip: One should use the
above function in order to discover the installed languages on the target
machine.
The next two functions force the keyboard
layout to be changed. On my machine the Hebrew and English layouts are
installed, one may add additional languages upon demand, using the appropriate
language identifier.
public static void Hebrew()
{
//load and activate the layout for the current thread
LoadKeyboardLayout(LANG_HE_IL,
KLF_ACTIVATE);
}
public static void English()
{
//load and activate the layout for the current thread
LoadKeyboardLayout(LANG_EN_US,
KLF_ACTIVATE);
}
Add a new C# windows application and place
3 buttons as shown below: