如何更改Windows窗体应用程序中特定控件的输入语言?

问题描述:

我想当焦点进入 TextBox 时,将语言更改为特定语言(例如波斯语),而焦点离开 TextBox时,将语言更改为之前设置的原始语言。

I want when the focus enters in a TextBox, change the language to an specific language (for example persian) and when the focus leaves TextBox, change the language to original language which was set before.

如何在特定控件处于打开状态时更改Windows窗体应用程序中的输入语言专注?

How to change input-language in a windows forms application when a specific control is focused?

这是我尝试过的方法,但是我不希望用户按任何键,而是要自动更改语言。

Here is what I tried, but I don't want the user press any key, I want to change the language automatically.

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if(e.Shift && e.Alt)
    {
        MessageBox.Show("***language of keybord changed***");
    }
}


您可以使用 InputLanguage.CurrentInputLanguage

You can change the input language programmatically using InputLanguage.CurrentInputLanguage.

足以处理 Enter 事件并设置 InputLanguage.CurrentInputLanguage 转换为所需的语言,并处理 离开 事件并将其设置回先前选择的输入语言。

It's enough to handle Enter event of your control and set the InputLanguage.CurrentInputLanguage to desired language and also handle Leave event of the control and set it back to previous selected input language.

在下面的代码中,我将输入语言设置为波斯语当我输入 TextBox1 并在离开控件时将其设置为以前的语言时:

In the below code, I set the input language to Persian when I enter TextBox1 and set it to previous language when I leave the control:

InputLanguage original;
private void textBox1_Enter(object sender, EventArgs e)
{
    original = InputLanguage.CurrentInputLanguage;
    var culture = System.Globalization.CultureInfo.GetCultureInfo("fa-IR");
    var language = InputLanguage.FromCulture(culture);
    if (InputLanguage.InstalledInputLanguages.IndexOf(language) >= 0)
        InputLanguage.CurrentInputLanguage = language;
    else
        InputLanguage.CurrentInputLanguage = InputLanguage.DefaultInputLanguage;
}

private void textBox1_Leave(object sender, EventArgs e)
{
    InputLanguage.CurrentInputLanguage = original;
}

要测试该示例,您应具有 fa-IR 作为操作系统上安装的输入语言,否则会将语言设置为默认输入语言。您可以使用操作系统上安装的另一种区域性输入语言。

To test the example you should have fa-IR as input language installed on your OS, otherwise it will set the language to default input language. You can use another culture input-language which you know installed on your OS.

注意:如果您在表单中广泛需要此功能,作为一个想法,您可以创建扩展程序提供程序组件,提供了 InputLanguage 属性。这样,您可以在设计时设置属性。这就是 ToolTip HelpProvider 之类的组件的工作方式。

Note: If you extensively need such feature in your forms, as an idea you can create an Extender Provider component providing an InputLanguage property. This way you can set the property at design-time. That's the way that components like ToolTip or HelpProvider works.