有没有一种方法可以在C#中已安装的Windows键盘布局之间进行切换?

时间:2019-02-17 18:23:08

标签: c# windows keyboard

我有两个文本框,一个用于英语,一个用于俄语。为了易于使用,我想知道c#中是否有某些内容可以告诉我的系统切换到已安装的键盘布局之一。

然后,我计划设置一种方法,以使其中一个文本框成为焦点。

因此,当俄语框处于焦点位置时,将使用Windows俄语键盘布局,反之亦然。

我在网上搜索了一下,但没有找到任何种类。因为我希望它早点完成,所以我做了一个变通办法,只是使用Input-simulator模拟了在Windows上切换键盘布局所必需的按键。现在,我正在寻找更好的解决方案。

Public Form1()
{
   // I use the method when either of the text-boxes are used.
   // When I find a better solution, there will obviously be two separate methods
   txtRussian.GotFocus += SwitchKeyboard;
   txtEnglish.GotFocus += SwitchKeyboard;
}
private void SwitchKeyboard(object sender, EventArgs e)
{
   // shift alt for keyboard layout switch
   sim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.SHIFT,VirtualKeyCode.LMENU);
   // LMENU (Left Alt) tends to still be pressed after you he finished the modified keystroke.
   // So that makes any first key the user presses be the "LAlt + {a key}" instead of just a key.
   // By normally simulating its press again the issue is gone
   sim.Keyboard.KeyPress(VirtualKeyCode.LMENU);

}

当然,这不是我真正想要的,因为每当您交替进入和退出选项卡并重新关注文本框时,它只会切换到已安装的下一个键盘布局,而不是指定的键盘布局。文本框的含义。

是的,有没有一种方法可以使用C#切换到指定的Windows键盘布局?

1 个答案:

答案 0 :(得分:0)

System.Windows.Forms命名空间中有“ InputLanguage”类。 您可以使用“ InputLanguage.CurrentInputLanguage”属性来更改当前使用的键盘布局。

关于stackoverflow的另一篇文章是: C# - Automatically switch between two different IME in the same keyboard layout

但是,您只能用它更改输入语言,而不能更改语言内部的布局。但是我认为您需要更改输入语言。 如果还需要更改语言的输入布局,可以通过设置TextBox的.ImeMode属性来完成。