Introduction
In general, developers want to set the layout of keyboard prior to application localized language. In this demonstration, I will develop a simple Windows application with custom control in type of text box. So, we can make the default input language of this text box as property.
Using the Code
The code is separated into two parts, one of them deals with keyboard layout and the other is a client which tests this.
- For better performance, get the machine installed language as follows:
public static InputLanguage GetInputLanguageByName(string inputName)
{
foreach (InputLanguage lang in InputLanguage.InstalledInputLanguages)
{
if (lang.Culture.EnglishName.ToLower().StartsWith(inputName))
return lang;
}
return null;
}
- Set your preferred language at run time:
public void SetKeyboardLayout(InputLanguage layout)
{
InputLanguage.CurrentInputLanguage = layout;
}
Remember the last used language before leaving the control if you intend to put editing controls with a different language in the same Windows Form.
Points of Interest
In the previous version of changing keyboard layout in this applicatoin, the code below was used.
The disadvantage of this is that importing external DLLs in the applications slows down the applications on Windows 7.
[DllImport("user32.dll")]
private static extern long GetKeyboardLayoutName(System.Text.StringBuilder pwszKLID);
[DllImport("user32.dll")]
private static extern long LoadKeyboardLayout(string pwszKLID, uint Flags);