Tuesday, March 27, 2007

Changing Keyboard Layout (Input Language) in C#

I've been asked on how to change the keyboard layout when the application is loaded, e.g. when your localized application is starting up you need to set the keyboard layout to Persian (farsi).

You may need a snippet like this :


private InputLanguage GetFarsiLanguage()
{
//Enumerate through InstalledInputLanguages which contains
//all the keyboard layout you've installed in your windows.
foreach (InputLanguage lang in InputLanguage.InstalledInputLanguages)
{
if(lang.LayoutName.ToLower() == "farsi")
return lang;
}

return null;
}

public void YourMethod()
{
InputLanguage lang = GetFarsiLanguage();
if(lang == null)
throw new NotSupportedException("Farsi Language keyboard is not installed.");

//Set the current language of the system to
//the InputLanguage instance you need.
InputLanguage.CurrentInputLanguage = lang;
}

Submit this story to DotNetKicks Shout it

3 comments:

Mortaza said...

Nice code, and this code used old API calls:

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int ActivateKeyboardLayout(int HKL, int flags);

public void SetLanguage(string WhichLanguage)
{
bool IsNT = true;
try
{
int ReturnValue;
if ((WhichLanguage == "Fa"))
{

if ((IsNT == true))
{
ReturnValue = ActivateKeyboardLayout(1065, 0);
}
else
{
ReturnValue = ActivateKeyboardLayout(1025, 0);
}
}
else
{
ReturnValue = ActivateKeyboardLayout(67699721, 0);
}
}
catch
{

//Error Handling...
}

}

Abdolhosein Vakilzadeh Ebrahimi said...

Moteshakkeram

ammar.w said...

Thank you