[C#] Windows Formアプリの多言語対応

C#で作成したアプリを、複数の言語で表示したい場合の作成方法。
また忘れそうなので備忘録として。。


 

言語ごとの文字列情報

日本語、英語、中国語、韓国語・・・など言語ごとの情報はソリューションエクスプローラーの
プロジェクト>Properties>Resources.resx に保存する。

デフォルト言語(通常は英語)は、”Resources.resx”に保存しておき、
他の言語は別ファイルとして同様のファイルを保存する。
例えば、日本語の場合は、”Resources.ja-JP.resx”など。

で、これらリソースの中に各言語の変数と文言を定義しておく。

例)
今回の例では、2つの文言(変数)を定義。

Resources.resx(英語)の定義:

 

Resources.ja-JP.resx(日本語)の定義:

 

プログラムソース

上記Resourcesで定義したSelectLanguageと、Messageをプログラムから呼び出す。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Threading;
using WindowsFormsApp1.Properties;
using System.Globalization;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox1.Items.Add("English");
            comboBox1.Items.Add("Japanese");
            comboBox1.SelectedIndex = 0;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBox1.Text)
            {
                case "Japanese":
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("ja-JP");
                    break;
                case "English":
                default:
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("");
                    break;
            }
            label1.Text = Resources.SelectLanguage;
            label2.Text = Resources.Message;
        }
    }
}

デザイン

Formのデザインは、以下の通り。
ラベル2つと、コンボボックスを配置しておく。

 

実行

 
 

Tagged

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA


*