Changing the input language in a textbox at runtime

Today, I'll talk about changing the input language for a textbox at runtime, in VS 2005. The might have two textboxes and each would expect a different input language. In my example, I need TextBox1 to receive Arabic input, while TextBox2 should receive English input.

These are the steps to do so:
Step 1: Enumerate the InputLanguage available on your machine, get the keyboard for Arabic and English. You don't really know the available keyboards that are installed on the user machine, so you better validate that the keyboard exists
Step 2: Handle the TexBox.Enter event.
Step 3: Load the relevant Keyboard.
Step 4: Reload the default Keyboard, when you no longer need the Arabic Keyboard. To simplify my solution I assumed that I'll change the keyboard to English only on TextBox2. On the other hand, you may change the inputlanguage on TextBox1.Leave.

This is the actual code (in VB, to please VB developers :))

Private ArabicInput As InputLanguage
Private EnglishInput As InputLanguage
PrivateSub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  ' Set the default as the current Inputlanguage
  ArabicInput = InputLanguage.CurrentInputLanguage
EnglishInput = InputLanguage.CurrentInputLanguage
  'Iterate to find the available Arabic and English Keyboards
  Dim count As Integer
  count = InputLanguage.InstalledInputLanguages.Count
  For i As Integer = 1 To (count - 1)
   If InputLanguage.InstalledInputLanguages(i).LayoutName.Contains("Arabic") = True Then
    'Found an Arabic Keyboard
    ArabicInput = InputLanguage.InstalledInputLanguages(i)
   Else
    If InputLanguage.InstalledInputLanguages(i).LayoutName.Contains("English") = True Then
     'Found an English Keyboard
     EnglishInput = InputLanguage.InstalledInputLanguages(i)
    End If
  End If
 Next i
End Sub
Private Sub TextBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Enter
InputLanguage.CurrentInputLanguage = ArabicInput
End Sub
Private Sub TextBox2_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.Enter
InputLanguage.CurrentInputLanguage = EnglishInput
End Sub
 

I hope this helps :)