代码改变世界

创建全球化的 Windows Mobile 应用程序

2008-05-13 17:25  Scott Wong  阅读(1692)  评论(8编辑  收藏  举报

下文将介绍如何创建一个全球化的应用程序,使其自动在中文版 Windows Mobile 下显示中文UI,在英文版Windows Mobile 下显示英文UI。同时,该应用程序还允许用户在中文版 Windows Mobile 下手动切换到英文UI。

一、创建本地化资源

首先将 Form1 控件的 Localizable 属性设置为 True,再将 Language 属性设置为“中文(简体)”。然后将 button1 的 Text 属性修改为“按钮”,将 label1 的 Text 属性修改为“标签”,保存。

 image

这时,在解决方案资源管理器中会多出一个 Form1.zh-CHS.resx 文件,这个文件就是 Form1 的简体中文资源文件。

image

将 Language 属性设置回“Default”,Visual Studio 2008 将重新加载 Form1.resx 文件,button1 和 label1 的 Text 属性也恢复成了初始值。

image

在模拟器 CHS Windows Mobile 5.0 Pocket PC R2 Emulator 中运行该应用程序时,button1 控件和 label1 控件的 Text 属性显示的是简体中文。

在模拟器 USA Windows Mobile 5.0 Pocket PC R2 Emulator 中运行该应用程序时,button1 控件和 label1 控件的 Text 属性显示的是英文。

二、在多国语言之间切换

本来以为 .NETCF 中的语言切换会像 .NET 中一样容易,只要设置 System.Thread.CurrentThread.CurrentUICulture 属性就可以了,没想到 .NETCF 根本就不支持 CurrentUICulture 属性。在网上搜索之后,找到了这个解决方案。解决的办法很巧妙,简单说就是重写 System.ComponentModel.ComponentResourceManager 类的 ApplyResources 方法,使表单在初始化组件时加载用户选择的资源。

首先卸载项目,然后打开项目文件进行编辑,将 <Reference Include="System" /> 修改成 <Reference Include="System"><Aliases>global,ms</Aliases></Reference> 之后保存。

 image

重新加载项目,在 Program.cs 类中添加一个叫 CurrentCulture 的静态公开字段。

using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Globalization;

namespace SmartDeviceProject1
{
    static class Program
    {
        public static CultureInfo CurrentCulture = CultureInfo.CurrentCulture;

        [MTAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }
    }
}

再创建一个 ComponentResourceManager 类。

extern alias ms;
using cm = ms::System.ComponentModel;
using System.Globalization;
using SmartDeviceProject1;

namespace System.ComponentModel
{
    class ComponentResourceManager : cm.ComponentResourceManager
    {
        public ComponentResourceManager(Type type) : base(type) { }
        public override void ApplyResources(object value, string objectName, CultureInfo culture)
        {
            if (culture == null)
            {
                culture = Program.CurrentCulture;
            }
            base.ApplyResources(value, objectName, culture);
        }
    }
}

当执行到 InitializeComponent 方法时,以上代码将被执行。

给 button1 增加 Click 事件。

private void button1_Click(object sender, EventArgs e)
{
    Program.CurrentCulture = (Program.CurrentCulture.Name == "zh-CN")
        ? new System.Globalization.CultureInfo("en")
        : new System.Globalization.CultureInfo("zh-CN");
    foreach (Control control in Controls) control.Dispose();
    InitializeComponent();
}

在中文版 Winodws Mobile 中运行该应用程序,按下 button1 时该应用程序将使用英文资源。