[源碼]用c#建立支援多語言的應用程式

來源:互聯網
上載者:User

點擊下載原始碼

互連網無國界,越來越多的應用程式必須面對全球使用者了,如何設計一個支援多國語言的應用程式呢?

在.net2.0 中,m$ 為我們提供了一種簡單方便的方法, 使用資源檔

1.建立一個 Winform 應用程式, 建立一 Form ,名為 Form1,添加兩個按鈕 btnChinese, btnEnglish
2. 設定 Form1 的 Localizable 屬性為 true, 設定該屬性後,.net 將根據不同的語言,為應用程式產生不同的資源檔
3.設定各個控制項的文本(系統預設語言下)
4.更改 Form1 的 Language 屬性為想要支援的另一種語言,此例中我們選用 English
5.重新設定各個控制項的文本
 註:此時.net 將為 Form1 產生另一個資源檔,在本例中名為 Form1.en.resx
6. 如果有其它的語言要設定,請重複第4,第5步
7.編寫代碼 

private void btnChinese_Click(object sender, EventArgs e)
        {
            //更改當前線程的 CultureInfo
            //zh-CN 為中文,更多的關於 Culture 的字串請查 MSDN
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("zh-CN");
            //對當前表單應用更改後的資源
            ApplyResource();
        }

        private void btnEnglish_Click(object sender, EventArgs e)
        {
            //更改當前線程的 CultureInfo
            //en 為英文,更多的關於 Culture 的字串請查 MSDN
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en");
            //對當前表單應用更改後的資源
            ApplyResource();
        }
        
        /**//// <summary>
        /// 應用資源
        /// ApplyResources 的第一個參數為要設定的控制項
        ///                  第二個參數為在資源檔中的ID,預設為控制項的名稱
        /// </summary>
        private void ApplyResource()
        {
            System.ComponentModel.ComponentResourceManager res = new ComponentResourceManager(typeof(Form1));
            foreach (Control ctl in Controls)
            {
                res.ApplyResources(ctl, ctl.Name);
            }
        }

大致的代碼就完成了,此時點擊 “中文”按鈕,畫面切換為中文,點擊“英文”按鈕,畫面立即切換為英文

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.