Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
867 views
in Technique[技术] by (71.8m points)

c# - How to change input-language in a windows forms application for a specific control?

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.

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***");
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can change the input language programmatically using 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.

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;
}

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...