Change keboard language and layout globaly in vb.net

1.4k views Asked by At

I am making a program which is supposed to change keyboard inputs and layout globally. Any kind of help appreciated.

I have used this code before, but nothing happened:

InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new System.Globalization.CultureInfo("ZH-CN"));
2

There are 2 answers

0
Hans Passant On

Nothing happens on my machine either. I don't actually have that keyboard layout installed. So it just stays en-US and there's no exception.

You'll have to add the keyboard layout first. On Windows 8, that's done with Control Panel, Language, "Add a language" link, pick one of the Chinese keyboard layouts. Now it does work on my machine. The procedure is different on earlier versions of Windows, follow up at superuser.com if you need more help.

0
Mojtaba Rezaeian On

As hans mentioned your code requires user to have keyboard layout added from his/her windows language options. If you want to add it from code try this to temporary install your required keyboard layout from your codes:

[DllImport("user32.dll")]
static extern bool UnloadKeyboardLayout(IntPtr hkl);
[DllImport("user32.dll")]
static extern IntPtr LoadKeyboardLayout(string pwszKLID, uint Flags);

public class KeyboardHolder : IDisposable
{
  private readonly IntPtr pointer;
  public KeyboardHolder(int klid)
  {
    pointer = LoadKeyboardLayout(klid.ToString("X8"), 1);
  }
  public KeyboardHolder(CultureInfo culture)
    :this(culture.KeyboardLayoutId){}
  public void Dispose()
  {
    UnloadKeyboardLayout(pointer);
    GC.SuppressFinalize(this);
  }
  ~KeyboardHolder()
  {
    UnloadKeyboardLayout(pointer);
  }
}

and use it this way:

// install keyboard layout temporary
KeyboardHolder keyboard = new KeyboardHolder(new System.Globalization.CultureInfo("ZH-CN"));

// after finishing what you want clear added keyboard layout:
keyboard.Dispose();