Localization of Windows Forms in C

Embed Size (px)

Citation preview

  • 8/14/2019 Localization of Windows Forms in C

    1/10

    Localization of Windows Forms in C# with VS.NET

    IntroductionCreating applications that are ready for the international market has become a key tenantin any application today. The need is to create applications that can cater to variousdifferent countries, cultures as well as reduce the cost of developing and debuggingseparate applications for each country. Creating applications that are ready to cater todifferent countries of the world is called as Internationalization .

    Internationalization has two separate issues, which are often very confusing for developersto understand. These issues are Globalization and Localization .In laymans terms :Globalization refers to creating applications where the currency format, date format,numerical system might differ. For example, the currency symbol for USA Dollar is $ whilethe currency symbol for UK Pound is , hence your application supporting globalizationshould be able to automatically pickup the correct format from the users operating systemand use it.Localization refers to creating applications where the screen text, strings, pictures mightdiffer from language to language. (Please note I am not referring to programminglanguages here, but spoken languages! )

    In this short article I will cover the creation of a simple Localized Windows Formsapplication. So as you might have already guessed, it will deal with creating a WindowsForms application that displays differently in different languages.Since my knowledge of foreign languages except English is Zero, I will be working withHindi (I am not good at typing this too..) and English !!

    Prerequisites1) VS.NET v7.0.9466 (.NET SDK v1.0.3705)

    2) Windows 2000 (I guess admin access might be required..).And please backup your stuff!!3) Basic understanding of C# and Windows Forms4) If you do not have the necessary font's installed on your computer, parts of this articlemay look garbled! Only way out is to install the necessary fonts.

    Setting-up Windows 2000 to support Hindi LanguageOne of the good features of Windows 2000 is that you can work with multiple languagesfrom within the same OS. But by default not all languages get installed (to save space andstartup time..) so you will have to first install the Hindi language fonts if they are not

    already installed.Go to Start menu -> Control Panel -> Regional Options to start the Regional Optionsdialog (Figure 1).

  • 8/14/2019 Localization of Windows Forms in C

    2/10

    Figure 1: Regional Options Dialog

    In the Regional Options dialog's General tab , check if the Indic language is selected; if not, select it and click OK . This will install the necessary Indian fonts for Hindi, Marathi,Gujarati, Konkani, Tamil etc. This step might ask you for the Windows 2000 Installation CD,so keep it handy, and it might also ask for a reboot.

    Once the machine reboots and the necessary fonts are installed again start the sameRegional Options dialog, and go to Input Locales tab and click Change . The TextServices dialog that shows, will allow you to select keyboard settings to use. Click Add toadd a new Keyboard Layout , from the Add Input Language dialog, select Hindi and clickOK .

  • 8/14/2019 Localization of Windows Forms in C

    3/10

    Figure 2: Text Services Dialog

    Figure 2, shows the Text Services dialog updated after I have added the Hindi keyboard.Here you can setup the Language Bar , and Key Settings so that you can easily shift

    between Hindi and English keyboards, but this is clearly out of the scope of this article, soexplore this stuff yourself.Also you will find that the Default Input Language dialog lets you select the defaultlanguage for your keyboard. Later in this article I will ask you to shift from English to Hindikeyboard layouts, this is the place you do that, I will not be mentioning it again!!

    How does .NET Handle Localization??.NET applications rely on Resource files (*.resx) to deal with Localization. The logic issimple, every bit of resource like label string, menu string, pictures, error messages,control size and location, etc are stored in these XML formatted resource files. Hence foreach different language your application will support you create a new resource file andplace the relevant translation (translation to be done by a human translator) of the stringsand pictures into the resource files. At runtime the appropriate resource file is selected andthe resources are used from it to display the necessary UI, making your single applicationlocalized..NET follows a consistent naming pattern for resource files so that the correct resource fileis selected. The default resource file is saved as .resx. (Where ClassName isthe name of the class that hosts the Main method to start the application.) Now for other

  • 8/14/2019 Localization of Windows Forms in C

    4/10

    languages you have to utilize the Culture Name for that language. MSDN documentationstates that, The culture names follow the RFC 1766 standard in the format "-", where is a lowercase two-letter code derived from ISO 639-1 and is an uppercase two-letter code derived from ISO 3166. Hence our Hindi resource file will be named .hi.resX. (Where hi is the culturename for Hindi ).If you have the VS.NET Documentation installed check out the following link to get a full list

    of Culture Names.[ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemGlobalizationCultureInfoClassTopic.htm]

    Lets Kick some Code!Finally, we start writing our application!! I am assuming that you are familiar with VS.NET,and so I will not be describing small little steps The source code is attached, you can referto it if you have doubts!

    1) Start VS.Net and create a new Windows Application project, call it asLocalizationDemo .

    2) Drag 1 GroupBox, 2 RadioButtons and 1 Button on to the Designer, and make the Formlook like figure 3.

    Figure 3: Form Design

    4) Now, right-click the LocalizationDemo Project in the Solution Explorer and add a NewWindows Form with the name Form2.cs .

  • 8/14/2019 Localization of Windows Forms in C

    5/10

    5) Add a Label, PictureBox and a Button on Form2 as shown in figure 4. I have set thePictureBox to show a custom bitmap (English.bmp) I have created.

    Figure 4: Form2 Designer

    6) Double-click the Close button in the Designer window so that we can write theEventHandler for the Click event of the button. In the event handler, we write nothing fancybut just a simply call the Hide method on the form, as shown below.

    this.Hide();

    7) Switch back to the Form2 Designer window and select the form in the Designer; andfrom the Properties window set the Localizable property of this form to true, indicatingthat this form supports Localization .

    8) While Form2 is selected in the Designer window, from the Properties window, change theLanguage property from (default) to Hindi. This will prompt VS.Net to add anotherResource file in the project with the name Form2.hi.resx . (I hope you remember why theparticular naming style is adopted !!).Please remember that all the changes that you make from here on to the componentsproperty will only get reflected while the user is viewing the application with the culture

    Hindi. In case you have added some new controls, you will have to switch back to theDefault Language property of the Form and again make the changes in the defaultlanguage also. This way you have to keep switching between the different languages yousupport in you applications and make the necessary UI changes to support all the differentlanguages your application supports.

    9) Now time to code in Hindi!! Go to Regional Options and change the default Keyboard toHindi (I hope you remember how to do this!!).

  • 8/14/2019 Localization of Windows Forms in C

    6/10

    10) Many times on English version of VS.NET source code files are saved in W esternEuropean (Windows) - Codepage 1252 format, hence if you try to directly enterUnicode Characters in Properties window it does not work correctly. Hence switch to codeview for Form2 and then from File menu -> Advanced Save Options dialog change theEncoding to Unicode (UTF-8 with Signature) - Codepage 65001 and click OK . Thisstep will ensure that in future the source code file is saved in UTF-8 format.

    11) Switch back to Design view and change the Text property of the Label to reflect (Hello in Hindi) and also change the Font to Mangal . Then change the Text property of the button to (Close in Hindi). Lastly, I have also changed to PictureBox to showanother picture. The changes shown look like figure 5.

    Figure 5: Hindi translation of Form2

    And if you are wondering how I wrote and , well with a little bit of practice youtoo will get away with it, but I will give it out this time, use the following keystrokes tomake the word:

    - vcmdls yxo

    12) Go back to the Regional Options dialog and re-set the default keyboard to English so

    that we can resume with our coding in English! If you forget this step, then you might startgetting varying response from application that are not designed to support Localization!!You might even have to restart VS.NET, if it still keeps typing in Hindi!

    13) Close the Form2 designer, and open the Form1 in the VS.NET designer window. Oncethe Form1 is open in the Designer window, double-click on the Start Application button sothat we can write the Event Handler for the Click event of the button.

  • 8/14/2019 Localization of Windows Forms in C

    7/10

    14) The code snip below is the EventHandler of the Start Application buttons Click event.Here, depending on which RadioButton is checked, I create an instance of the CultureInfoclass and assign it to the CurrentUICulture property of the current thread.This will make the necessary switch between the different UIs.

    private void button1_Click(object sender, System.EventArgs e){

    if( this.radioButton1.Checked ){

    //Get the Default installed cultureSystem.Threading.Thread.CurrentThread.CurrentUICulture =

    System.Globalization.CultureInfo.InstalledUICulture ;}else if( this.radioButton2.Checked ){

    //Get the Hindi cultureSystem.Threading.Thread.CurrentThread.CurrentUICulture =

    new System.Globalization.CultureInfo("hi") ;}Form2 f2 = new Form2();

    f2.Show();

    }

    14) Thats It !! Build your code and run it, if you followed the steps correctly the applicationshould build and work correctly!!

    Some ImprovementsHere is a list of improvements you could make,1) Currently, I am asking the user to give the language preference every time he runs theapplication. It would be a better design if you would ask for the users language preference

    only once at install time, and then store the language preference into the applicationconfiguration file.2) This applications takes it for granted that the default language of the user is English, inyour application you should not make this assumption, instead you should build anadditional English (en) resource file separately an not rely on the default resource file.

    Conclusion.NET has provided an extensive platform that support Internationalization. VS.NETharnesses this and helps you easily create applications supporting Internationalizations.This article showed you one way of working with Localization through VS.NET.

    Saurabh Nandu - 16 June 2002

  • 8/14/2019 Localization of Windows Forms in C

    8/10

    Your Ratings / Comments

    Viewer Ratings/Comments Rating Description 5 fdsg - ewq on 6/24/2002 10:44:00 AM

    5Excellent. Your writing skill has definitely improved Saurabh. Very clearly written article -Sai on 7/2/2002 12:54:00 PM

    4 Nicely done. - Tokunboh Odusami on 7/14/2002 3:32:00 AM 1 - gb on 8/11/2002 10:07:00 AM 4 Nice demonstration - xi on 9/25/2002 7:50:00 AM

    Just Comments

    could you please email me with an answer to the following questions if you have them.FIrstly how do you localise the "canned" dialogs provided in .NET (for example thestandard print dialog) Secondly when you distribute your app do you see the installation oif the ruhntime in the correct language ? cheers Richard - richard bradwell on10/22/2002 3:51:00 PM

    1

    Excellent , funtastic done. One question.... The applcaion as you said requires the supportto hindi language from microsoft. Providing the microsft support just includes installing thefonts. I tried with different fonts, but it doesn't work. Why? - chandan on 10/24/20021:27:00 AM

    Just Comments no - mohammad on 10/28/2002 9:17:00 AM

    5

    Excellent! I used your code to help me in my work. But I have a question. This is possibleto create a form and switch language and not creating a new form each time? Here is my

    problem, I created a bilingual application and I add the possibility to switch betweenenglish and french. When I click on the button to switch language, it's create a new form.Do you know how I can display only one form at the time? Thanks! :) - Nathalie on11/5/2002 11:23:00 AM

    4 - Denny on 11/16/2002 8:24:00 AM

    5This is fantastic article describing every step in detail. Precautions and references are alsogiven. It gives neat example with which nay one can start building. Great - balachandar on11/20/2002 9:14:00 AM

    4 Not to bad at all. Just wondering is that all there is to it? Are there any other techniques that

    would be usefull. - Alex Busu on 1/10/2003 10:59:00 PM 3

    How to change the language in the Windows Xp as there is no option like that in the W2K -Zeeshan on 1/23/2003 8:40:00 AM

    5

    Your site is the only one I found that explained that I needed to do the translation myself.Hence knowing multiple languages and changing my keyboard settings etc. Microsoftdiscussed all the fluff but never said you must hand type your resource files in the languageof choice. Thanks a bunch. - Audean on 1/30/2003 10:40:00 AM

    Just Commentsi am font designer who run on linux mangal font - karambir singh Rohilla on2/11/2003 5:08:00 AM

    Just Comments hello - abc on 3/5/2003 2:19:00 PM 5 - ali on 3/29/2003 5:34:00 AM 5 Why sai is maraving you - santy on 5/10/2003 11:16:00 AM

    5 to Nathalie - it is possible to do what you want. Seehttp://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=211 to change languagein current form, I did (as he recommended) 1) you need a resource manager variable in theform class private ResourceManager m_ResourceManager = newResourceManager("TabbedWindow.Form1",System.Reflection.Assembly.GetExecutingAssembly()); 2) then in the event handler, youneed to set the Culture, and re-get the strings of the particular elements you want to change(I changed some tabs in mine) ex: //Get the French cultureSystem.Threading.Thread.CurrentThread.CurrentUICulture = new

  • 8/14/2019 Localization of Windows Forms in C

    9/10

    System.Globalization.CultureInfo("fr-FR") ; this.tabPage1.Text =m_ResourceManager.GetString("tabPage1.Text"); this.tabPage2.Text =m_ResourceManager.GetString("tabPage2.Text"); this.tabPage3.Text =m_ResourceManager.GetString("tabPage3.Text"); this.tabPage4.Text =m_ResourceManager.GetString("tabPage4.Text"); - Todd Harvey on 5/31/20037:25:00 PM

    5

    Its just excellant. Though I have a question here, how do you manage the database drivenapplication. Is this conversion meant just for the static fields like labels ,etc not for the user input. If we can then how do we do that...having seperate database for each language ? plemail me if you have any idea about this. Thanx - RSharma on 7/20/2003 1:47:00

    PM

    5

    Well this was a nice artice to get started for someone like me... But lot of things can beadded to explain more unctionality of the resx files and various ways of changing languageat runtime... Nice job anyway Regards- Varun Jain - Varun on 8/22/2003 1:16:00AM

    Just Comments

    Its really good one. but in asp.net we cannot get the thing in the same way mentionedabove. we have to use the resourse manager to obtain the multilingual values. or is thereany other solutions?if so please provide them. and how coud the input boxes( text box) canget the multilingual values from the user (we are not setting the values at design time or runtime) ? do we have to set the fonts dynamicaly? - GS on 8/22/2003 5:59:00 AM

    4 ssdfdsfsd - dsd on 11/10/2003 5:10:00 AM

    4

    Hi, I was wondering if there is a way to take a Unicode string and find out what language

    (or local) the string is? my aim is to have a bi-lingual program that say knows if a string isin arabic or in another lanuage. Thanks Mark - Mark on 1/8/2004 5:26:00 AM

    1This site is not helpful in my opinoin i think its complete rubbish hai. Leken baat ka choodoek din kya baaz hua hai. raaz ek pyaar humko ne wali ka. I give it one cup as a rating -Arband Nandi on 1/16/2004 4:49:00 PM

    4A good example of using Localization. I suggest to provide a batch file to compile theapplication. Everyone may not have Visual Studio .Net IDE. - Rajshekhar Bashetti on1/28/2004 6:46:00 AM

    5 it is . Is it possible same as telugu - Sivaprasad on 2/23/2004 11:39:00 PM 5 Good and explicit sample - Eralper on 3/16/2004 4:49:00 AM

    3

    Nice article, but I'm still left with two questions: 1. when the user changes the language of the computer in W2K using Control Panel (Regional Options, etc.), what is the event I needto capture so my app can switch languages without having to be restarted? I triedInputLanguageChanged but my event handler is not fired. 2. How do I change the languagein a form that is already displayed? That is, if I select French while my form is displayed inEnglish, how do I make it change the texts to French? I tried settingThread.CurrentUICulture to new CultureInfo("fr-CA") and calling Form.Refresh(), itdoesn't do anything. - dvader on 4/15/2004 9:15:00 AM

    5in one word "Excellent"...i was making an assignment for office and this article fullydescribed the particular thing which was needed by me....excellent...i hope that the writer will continue to write more aricles. - Beenish on 7/14/2004 5:44:00 AM

    3

    i have a big problem.can you help me? my problem is this: as you have told, i change thelocalizable propert to true and language to German.but i havn't done any changes on thecontrols.because i want to do these changes in resx file all together.but if i don't make anychanges on any controls, in resx file i can't enter a value for german. - gulnur on10/27/2004 2:20:00 AM

    4 Nice on.... sunil.... www.suncindia.com - Sunilkumar Shinde on11/8/2004 1:12:00

    AM 5 Thank you! - Sebastian on 12/7/2004 10:40:00 AM

    5

    quite nice, this article is of immense help. Even i had the same problem as Nathalie , if uwrite a function to update the UI, then ur translating only the text/labels. I re-initialize theform by doing something like: this.Controls.Clear(); InitializeComponent(); this will alsotake care of reloading the form with set culture + resize any controls from the resp. resxfile. - vishnu on 5/25/2005 10:52:00 AM

  • 8/14/2019 Localization of Windows Forms in C

    10/10

    5 - Lubna Sorour on 6/7/2005 8:48:00 AM

    Just Comments

    It is a nice tutorial for me in order to hold my project tight(ie Inventory Control System inUrdu). But I am facing a problem regarding this Concept, Iwant to enable the text box tohold localization property too. Although it works when I change my regional & Languagesetting in Control Panel. Is there any way to change these setting in .NET during coding. sowhen I switch to another language text box will restore the specified language behavior i.eRTL . Iam very thankful to U if U help me regarding this matter .U may mail me Inorder toreply my problem - Yasir on 8/8/2005 11:18:00 AM

    5

    Excellant,it is very usefull. But i have one question , i read the comments of "Nathalie" andthe response provided by you.But you also used only one form right,you started explainingagain as if you have used two forms, there i didn't get.Pls do not forget to answer myquestion. - Manohar on 8/11/2005 5:34:00 AM

    4

    The aticle that you just presented was very claer and useful. I have been working on your code and I want o change the image on the picture, say for english i would place theamerican flag and for hindi the indian flag, and i want to get the images from a resource filealso but as of the moment i don't know how. I would like to request from you if you couldhelp me on this. thanks in advance and more power. p.s. if you would be so kind to emailme the answer. ;) - Efren Duran on 8/22/2005 9:13:00 PM

    Just CommentsHi Guys , I just want to know can I enable more language in given cultureUIinfo object.My applicaton requirement is use Sindhi (Pakistan regional language). It is possible to used- Tariq Ali on 9/8/2005 6:07:00 AM

    2

    i want to type in different langage as per user choice in my web page.user have to selectlanguage name from drop down list. and in text box ,the type character willbe from thatspecific language.(no manuall seting in regional and language setting) ??? - nilesh kumaron 9/13/2005 2:36:00 AM

    4 Hey its quite simple and beautifully written. Cheers!!! - simon on9/13/2005 6:28:00

    AM 1 jj0909 - 0909 on 10/15/2005 4:15:00 AM

    Just CommentsI want to display as in in we call good same in hindi Good not the hindi meaning of that isit possible - uday on 10/27/2005 4:56:00 AM

    Just Comments Excellent work Go head man you are great - Prasad on 11/16/2005 11:26:00 PM