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

Viewed 11940

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***");
    }
}
3 Answers

For people seeking similar solution for other languages that are available in many countries (e.g.: Arabic, there is "ar-SA","ar-EG" and many others) You can use this to get the correct language regardless of the country:

For WinForms: VB:

originalInputLang = InputLanguage.CurrentInputLanguage
Dim lang = InputLanguage.InstalledInputLanguages.OfType(Of InputLanguage).Where(Function(l) l.Culture.Name.StartsWith("ar")).FirstOrDefault()
        If lang IsNot Nothing Then InputLanguage.CurrentInputLanguage = lang

C#:

originalInputLang = InputLanguage.CurrentInputLanguage;
var lang = InputLanguage.InstalledInputLanguages.OfType<InputLanguage>().Where(l => l.Culture.Name.StartsWith("ar")).FirstOrDefault();
if (lang != null) {
    InputLanguage.CurrentInputLanguage = lang;
}

For WPF: VB:

Dim origianl As Globalization.CultureInfo //outside the event handler



// in the entered event handler:
origianl = InputLanguageManager.Current.CurrentInputLanguage
Dim newLang = InputLanguageManager.
    Current.
    AvailableInputLanguages.
    OfType(Of Globalization.CultureInfo).
    Where(Function(i) i.Name.StartsWith("ar")).
    FirstOrDefault()
If newLang IsNot Nothing Then InputLanguageManager.Current.CurrentInputLanguage = newLang

//in the leave event handler:
InputLanguageManager.Current.CurrentInputLanguage = original

C#:

System.Globalization.CultureInfo original; // outside the event handlers

// in the enter event handler:
original = InputLanguageManager.Current.CurrentInputLanguage;
var newLang = InputLanguageManager.
    Current.
    AvailableInputLanguages.
    OfType<System.Globalization.CultureInfo>().
    Where(l => l.Name.StartsWith("ar")).
    FirstOrDefault();

if (newLang != null)
{
    InputLanguageManager.Current.CurrentInputLanguage = newLang;
}

// in the leave event handler:
InputLanguageManager.Current.CurrentInputLanguage = original;

If you want to change the system input language (so that every application will use the selected language) you can simply use SendKeys which simulates keyboard key presses:

SendKeys.Send("%+");

The string represents Alt + Shift which in Windows changes the input language by default.

Related