Sunday, May 15, 2011

Tab and Newline Characters in Resource Files

Tab and newline characters cannot be added to resource files (.resx) by using “\t” or “\r\n”. This is because these escape sequences are C# specific while resource files are language independent.

Instead, you must explicitly add the tab or newline. If using the Visual Studio resource editor, you cannot insert a tab into a cell. The easiest way to get around this is to type your string (with tabs) in Notepad, then copy and paste into the resource editor. Newlines can be inserted directly into the resource editor by pressing Shift+Enter.

If you have to use the  “\t” in your resource file, then you can add code to replace the “\t” with actual tab characters:

string s = Resources.ResourceName.Replace("\\t", "\t");

Similarly, you can replace the “\n” with actual newline characters:

string s = Resources.ResourceName.Replace("\\r\\n", "\r\n");

Saturday, May 14, 2011

How to Auto Resize Button Depending on Text

If you need a button to automatically resize to fit the text it contains, then simply change the “AutoSize” property to “True”, the “AutoSizeMode” property to “GrowAndShrink”, and the “AutoEllipsis” property to “False”.

If you would like a minimum button size, then set the button Size property to what you would like the minimum button size to be and set the “AutoSizeMode” to “GrowOnly”.

Keep in mind that the UI layout and other elements may need to be adjusted since the button size is now dynamic.

Wednesday, May 11, 2011

CultureInfo.CurrentCulture for New Threads

The CultureInfo.CurrentCulture for each thread is independent. When a new thread is created, the CurrentCulture is set to the default system locale information, rather than the CurrentCulture of the calling thread. The following code demonstrates this:

using System;
using System.Globalization;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            CultureInfo cultureInfo = new CultureInfo("fr-FR");
            Thread.CurrentThread.CurrentCulture = cultureInfo;

            Console.WriteLine("Main Thread Culture: {0}"
                CultureInfo.CurrentCulture.DisplayName);

            Thread t = new Thread(NewThread);
            t.Start();
        }

        static void NewThread()
        {
            Console.WriteLine("New Thread Culture: {0}"
                CultureInfo.CurrentCulture.DisplayName);
        }
    }
}

The output is the following:

Main Thread Culture: French (France)
New Thread Culture: English (United States)