How to change the language in my WinForm? - c#

I am developing an application in c#. The current language of my system is French. What i want is when i open my application the language should be changed to English. Is there anyway by which i can perform this task. I tried to change the language through code but nothing seems to work.
Here is my code
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

I'm going to assume that you have your forms localized to both French and English. If that is the case, then once you run the code in your question, new forms you display will show in the new language.
If you want to change the language and have forms that are currently being shown redisplay their text in the new language, you have to put together something that responds to the culture being changed and update all the labels, radio buttons, and so on.
Fortunately, someone has already done this work for you:
http://www.codeproject.com/Articles/23694/Changing-Your-Application-User-Interface-Culture-O

Windows will not automatically translate your application, you need to provide these yourself and load them into language specific.
This article explains the process quite well. You're updating the culture which tells the system which resource files to use. Now you need to provide the text to show.

You have to reload forms (or switch language before you create any form)
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
Form1 form1 = new Form1();
form1.ShowDialog();
This assume, you are using satellite assemblies and already have form translated.
If you want to change keyboard layout (FR -> EN), then, while it is also possible, you better don't. As user may have his preference for which layout he want to use by default.

I can't replicate your problem here. The code should work fine in term of changing the way Double.Parse method works. Here is how I did the test :
string duit = "1.000.100"; //this is a valid number format in my current culture
string money = "1,000,100"; //but this is not valid
var culture = CultureInfo.CurrentCulture; //my current culture is indonesia (id-ID)
var duitDouble = double.Parse(duit); //parsed successfully
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
culture = CultureInfo.CurrentCulture; //now current culture is english (en-US)
var moneyDouble = double.Parse(money); //parsed successfully
Besides, I really suggest to rephrase your question and title to avoid misunderstanding. That will be good for you and people that intend to help. As you can see, most of the answers posted are not actually answering the question (the actual problem is indicated in OP's second comment in the question).

Related

Define a string based on culture info in C# Silverlight

I need to spell word "Colour" as "Color" in US format and as "Colour" in UK format. My applications works in these 2 countries. I need to change the spellings accordingly. I tried it with the following code :
string sample = "";
if (CultureInfo.CurrentUICulture.Name == "en-US")
sample = "Color";
else
sample = "Colour";
But this somehow doesn't seem to work.
In Silverlight the culture defaults to "en-US" regardless of the country you are actually running in.
You need to explicitly set the culture in the view class with the following code:
this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);
after having set the thread culture accordingly:
CultureInfo ci = new CultureInfo(GetEnterpriseCultureName(enterpriseCultureId));
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
return ci.Name;
You can also override the currency symbol and number separators in this as well.
Source
Then, once you've done that the simplest solution is to put your strings into a pair of resource files. One just called "Resource.resx" which is the default and another called "Resource.en-US.resx" (for example) if your default is the UK.
Then .NET will automatically select the correct resources based on the the culture of the thread.
The right way to deal with localization and region differences in spelling is to use the Silverlight Resource Manager that was included into the framework for exactly that sort of thing.
The Hierarchical Organization of Resources
To understand how resources are loaded, it is useful to think of them as organized in a hierarchical manner. A localized application can have resource files at three levels:
At the top of the hierarchy are the fallback resources for the default culture, for example, English ("en"). These are the only resources that do not have their own file; they are stored in the main assembly.
At the second level are the resources for any region-neutral cultures. A region-neutral culture is associated with a language but not a region. For example, French ("fr") is a region-neutral culture.
At the bottom of the hierarchy are the resources for any specific cultures. A specific culture is associated with a language and a region. For example, French Canadian ("fr-CA") is a specific culture.

Get language and country code (ISO 639-1)

Is there a solution for xamarin-ios to get the current culture in the format like (en_US, de_CH, ..)? I read so many articles in the web and here on stackoverflow. But I can't find a nice solution for this.
Following code snippet returns not this format everytime. Sometimes I get "gsw_DE" and so on (ISO 639-2 instead of 639-1)
NSLocale.CurrentLocale.Identifier;
My current solution is to do it by myself:
var languagecode = NSLocale.PreferredLanguages[0];
var result = String.Format("{0}_{1}", languagecode.Substring(0, 2), NSLocale.CurrentLocale.CountryCode);
Above workaround is from: Get iOS current language (including country code)
I need to make sure that I get the value in this format.
Is there another way? Thanks
We are still in the C# world, aren't we?
You can use CultureInfo.CurrentUICulture.Name and it'll give you "en-US" for "default" English and "en-GB" for English UK. Language settings are in General - Language & Region - iPhone Language.

WinRT apps and Regional settings. The correct way to format dates and numbers based on the user's regional settings?

I'm having some problems in Windows 8 Metro apps (XAML & C#) regarding the user's regional settings. It seems that the apps won't respect user's regional settings, so even if your Windows 8 is set to display dates and times in Finnish format, the apps will still display them using US-formatting. But this is such a big problem that there must be something I'm missing?
To test this I started by creating a WPF-application. The application just prints out the CurrentCulture and the formatted DateTime.Now:
private void Culture_Loaded_1(object sender, RoutedEventArgs e)
{
this.Culture.Text = System.Globalization.CultureInfo.CurrentCulture.DisplayName;
}
private void Date_Loaded_1(object sender, RoutedEventArgs e)
{
this.Date.Text = DateTime.Now.ToString();
}
Here's my default regional settings:
When run, the app displayed the date in Finnish format:
Then I changed the regional settings to US:
And when the app was run again, the culture and formatting changed:
This is as I expected everything to work and this is also how I expected WinRT apps to work.
So as a next step, I created a WinRT (XAML & C#) app with the same code and reverted the regional settings back to Finnish. The problem:
Even when I've defined through regional settings that the formatting should be "Finnish", the WinRT app displays the datetime with US-formatting. I then modified the app's project file and made fi-FI the default language:
This change also modified the app's culture:
Strange. I changed the Default Language back to its default value and the formatting was restored to US. I then created folders "Strings - fi-FI" inside the project and added an empty "Resources.resw" to the project. This empty file seems to be enough, as I was now getting the Finnish formatting:
As soon as I remove the empty resource file, the formattings reverts back to US:
Very strange.
This leads to few questions, but the main one I think is: Is it intentional that the WinRT-apps don't follow the user's regional settings like the WPF apps do?
It's been a while, but the question is not fully answered, so let me share my little research. Depechie is mostly right, but he provided only a link and wasn't really sure.
Yes, this unexpected change is intentional. We shouldn't use CultureInfo anymore as it contains legacy codes and Microsoft want us to use Windows.Globalization APIs instead.
To obtain current region we can use:
GeographicRegion userRegion = new GeographicRegion();
string regionCode = userRegion.CodeTwoLetter;
But as I noticed it contains only region information, there's no language code. To obtain language we can use:
string langRegionCode = Windows.Globalization.Language.CurrentInputMethodLanguageTag; // depends on keyboard settings
List<string> langs = Windows.System.UserProfile.GlobalizationPreferences.Languages; // all user languages, like in languages control panel
List<string> applicationlangs = Windows.Globalization.ApplicationLanguages.Languages; // application languages (user languages resolved against languages declared as supported by application)
They return BCP47 language tags in format language-REGION like "en-US" if language has dialects or just language like "pl" if the language doesn't have major dialects.
We can also set one primary language which will override all the rest:
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = "en-US";
(This is a persisted setting and is supposed to be used at user request)
There is also new API for date, time and numbers:
Windows.Globalization.DateTimeFormatting.DateTimeFormatter dtf = new DateTimeFormatter("longdate", new[] { "en-US" }, "US", CalendarIdentifiers.Gregorian, ClockIdentifiers.TwentyFourHour);
string longDate = dtf.Format(DateTime.Now);
Windows.Globalization.NumberFormatting.DecimalFormatter deciamlFormatter = new DecimalFormatter(new string[] { "PL" }, "PL");
double d1 = (double)deciamlFormatter.ParseDouble("2,5"); // ParseDouble returns double?, not double
There's really a lot more in Windows.Globalization APIs, but I think that this gives us the general idea. For further reading:
date & time formatting sample:
http://code.msdn.microsoft.com/windowsapps/Date-and-time-formatting-2361f348/sourcecode?fileId=52070&pathId=561085805
number formatting & parsing sample:
http://code.msdn.microsoft.com/windowsapps/Number-formatting-and-bb10ba3d/sourcecode?fileId=52249&pathId=1462911094
there's also a nice article titled "How to use patterns to format dates and times" on msdn, but I can add only 2 links
You can also find some topics about the issue on windows 8 dev center forum with some Microsoft employee answers, but they mainly send you to the documentation.
It is intentional. Microsoft is moving away from forcing applications to be in the language of the OS. Instead, each application uses information declared by the application (manifest languages, observable at Windows.Globalization.ApplicationLanguages.ManifestLanguages) and declared by the user (user languages, observable at Windows.System.UserProfile.GlobalizationPreferences.Languages) to determine how to display resources and globalized dates and times. This set of languages is called the application languages (observable at Windows.Globalization.ApplicationLanguages.Languages). The behavior you are seeing is because you are fiddling with the user languages and the manifest languages and you will get different application languages.
Could it be we now need to query other classes? Like the example given here: http://code.msdn.microsoft.com/windowsapps/Globalization-preferences-6654eb36/sourcecode?fileId=52104&pathId=236099476
This post still seems to be relevant even though it was asked two years ago.
I just came across it as I was looking for an answer to about the same thing.
I also wanted to display dates in the regional format in my WP8.1 WinRT app.
The information posted here helps, but it was a bit hard to piece it together.
This is what I came up with and it seems to work for me as the answer I needed:
using Windows.Globalization;
using Windows.Globalization.DateTimeFormatting;
private string FormatDate(int year, int month, int day)
{
GeographicRegion userRegion = new GeographicRegion();
string regionCode = userRegion.CodeTwoLetter;
var formatter = new DateTimeFormatter("year month day", new[] { regionCode });
DateTime dateToFormat = new DateTime(year, month, day);
var formattedDate = formatter.Format(dateToFormat);
return formattedDate;
}

How to know previously selected language in the localization?

I have two languages, English and Gujarati for UI. If, At the time of closing UI language is Gujarati, then at the opening time also language should be Gujarati. How do I know this: ?? the code for language selection is here.
ComboBoxItem englishLanguageItem = new ComboBoxItem()
{
Content = Strings.MainWindow_Language_Selection_English_Label
};
ComboBoxItem gujaratiLanguageItem = new ComboBoxItem()
{
Content = Strings.MainWindow_Language_Selection_Gujarati_Label
};
Please give some code regarding it.
Not sure if I understood your problem. You need to know what was the last selected language, so when your program is re-open, it comes up with that language?
If so, you have to save it somewhere, maybe on registry.
Here you can check how to do it: http://www.codeproject.com/Articles/3389/Read-write-and-delete-from-registry-with-C

Localization problem

I need to make a form that have to suport two languages (for now).
the two languages dont have the same look and also half of the form is not a like but it still have some similiarity beetwen them.
what is the best way to deal with this problem in a case of two different languages and above?
by the way, the program language that I use is C#.
10x
First, configure your project default language, you do this in the Project Properties, in the Assembly Information dialog, there's a "Neutral Language" setting at the bottom.
Set this to be your "default" language, the "main" language if you wish.
Then, make sure the form as it is now, is in that language.
To start translating and changing the form to comply with a different language, first set the "Localizable" property of the form to true, and then change the Language property to your second (or third, fourth, etc.) language.
Once you have changed that, you can start making changes. Make sure you don't delete items on the form, instead just set them invisible. Deletion is done for all languages, but invisible will thus only be set for the current language.
Keep switching back and forth between the languages to make adjustments.
To test your program in a specific language, execute this at the start of your Main method:
Thread.CurrentThread.CurrentCulture = new CultureInfo("code of that other language");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("code of that other language");
For instance, to test it with "Norwegian, Bokmål" language, which is my main language, the code you would use would be "nb-NO". To find the code you need to use, once you've changed the language of your form to the language you want to localize for, and saved, a new file will be added to the solution explorer with the right name.
For instance, for Form1, the following files will be present:
Form1.cs
Form1.designer.cs
Form1.nb-NO.resx <-- here's the localized content
Form1.resx
Now, having done this, there's plenty of other things you need to be aware of when making a localized application, I suggest you go read other questions on SO and on the web with more information, like these:
Best practice to make a multi language application in C#/WinForms?
Parsing DateTime on Localized systems
Pluralising and Localizing strings in C#
How do I best localize an entire app to many different languages?
I think a single global resource file for each language is better than having a resource file for each form for each language.
I recently did globalization of a winforms app with the help of the following link "Globalization of Windows Applications in 20 Minutes". Here are the steps for simplicity :
Create a text file say "data.en-US.txt" in the solution (<filename>.<culture string>.txt) in the format below :
Hello=Hello
Welcome=Welcome
This file "data.en-US.txt" is a resource text file in the English language.
Create a similar file in your desired language say German, so its filename will be data.de-DE.txt
Hello=Halo
Welcome=Willikomen
The first column are the labels which will be used as keys for referring the text.
Create a "data-en-US.resource" file out of the text files by using the command "resgen.exe data.en-US.txt",
Do this for all language files. Now in your solution you have 2 (or more, depending on the languages you want to support) data.<culture string>.resource files
Click all the .resource files and set "Build Action" property to "Content".
Click all the .resource files and set "Copy to Output Directory" property to "Copy Always / Copy If new".
Get the localized string using the code below in any of the forms :
string label = "Hello";
string cultureString = "de-DE" // [or "en-US"]
string strResourcesPath = Application.StartupPath;
CultureInfo ci = new CultureInfo(cultureString); ['cultureString' represents your desired language]
ResourceManager rm = ResourceManager.CreateFileBasedResourceManager("data", strResourcesPath , null); ["data" is the first part of the filename]
var answer = rm.GetString(label, ci); // here ans="Halo" as we selected de-DE

Categories

Resources