Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Changing Keyboard Layout

0.00/5 (No votes)
29 Jun 2010 2  
Programmatically switch keyboard layout in C#

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.

  1. 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; 
    } 
  2. 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);

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here