有需求或技術問題可以隨時跟我連絡 (MSN上線時)

2009年8月12日 星期三

簡體中文 繁體中文 轉換

UI Layout如下圖所示:


重要的Using:
using System.Runtime.InteropServices;

重要程式碼:
namespace 簡繁中文轉換
{
public partial class Form1 : Form
{
internal const int LOCALE_SYSTEM_DEFAULT = 0x0800;
internal const int LCMAP_SIMPLIFIED_CHINESE = 0x02000000;
internal const int LCMAP_TRADITIONAL_CHINESE = 0x04000000;

//Import WIN32API:LCMapString
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int LCMapString(int Locale, int dwMapFlags, string lpSrcStr, int cchSrc, [Out] string lpDestStr, int cchDest);


public Form1()
{
InitializeComponent();
}

private void button_Translate_Click(object sender, EventArgs e)
{
if (textBox_TC.Text != string.Empty)
{
textBox_SC.Text = ToSimplified(textBox_TC.Text);
}
else if (textBox_SC.Text != string.Empty)
{
textBox_TC.Text = ToTraditional(textBox_SC.Text);
}
}
///
/// 繁體轉簡體
///

/// 要轉換的繁體字:體
/// 轉換後的簡體字:体
public static string ToSimplified(string pSource)
{
String tTarget = new String(' ', pSource.Length);
int tReturn = LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_SIMPLIFIED_CHINESE, pSource, pSource.Length, tTarget, pSource.Length);
return tTarget;
}

/**////
/// 簡體轉繁體
///

/// 要轉換的繁體字:体
/// 轉換後的簡體字:體
public static string ToTraditional(string pSource)
{
String tTarget = new String(' ', pSource.Length);
int tReturn = LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_TRADITIONAL_CHINESE, pSource, pSource.Length, tTarget, pSource.Length);
return tTarget;
}
}
}

參考資料:Win32 Programmer's Reference LCMapString
尚有其他轉換功能,可以自行研究
LOCALE_SYSTEM_DEFAULT = 0x0800;
LCMAP_FULLWIDTH = 0x00800000; //LCMAP_FULLWIDTH (轉全形字)
LCMAP_HALFWIDTH = 0x00400000; //LCMAP_HALFWIDTH (轉半形字)
LCMAP_HIRAGANA = 0x00100000; //LCMAP_HIRAGANA (轉成平假名,日文)
LCMAP_KATAKANA = 0x00200000; //LCMAP_KATAKANA (轉成片假名,日文)
LCMAP_LINGUISTIC_CASING = 0x01000000; //LCMAP_LINGUISTIC_CASINGLCMAP_UPPERCASE (不明)
LCMAP_LOWERCASE = 0x00000100; //LCMAP_LOWERCASE (轉小寫,應該是英文)
LCMAP_SIMPLIFIED_CHINESE = 0x02000000; //LCMAP_SIMPLIFIED_CHINESE (轉簡體)
LCMAP_SORTKEY = 0x00000400; //LCMAP_SORTKEY (不明)
LCMAP_TRADITIONAL_CHINESE = 0x04000000; //LCMAP_TRADITIONAL_CHINESE (轉繁體)
LCMAP_UPPERCASE = 0x00000200; //LCMAP_UPPERCASE (轉大寫,應該是英文)


沒有留言:

張貼留言