知识要点:
1、LCMapString函数的功能与使用,具体查阅MSDN。
2、C#中如何调用API函数。C#2005中使用DllImport关键字,以及引用System.Runtime.InteropServices名字空间;之前版本使用sysimport关键字。
代码说明:
1、适合C# 2005,若为之前版本,请将
[DllImport("kernel32.dll", EntryPoint = "LCMapStringA")]
改为
[sysimport(dll = "kernel32.dll", name = "LCMapStringA")]
2、控件:TextBox:textBox1;
Button:button1;
Button:button2;
Button:button3;
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
//System.IO与System.Runtime.InteropServices手工加上
namespace WindowsApplication1
{
public partial class Form1 :Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender,EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter= "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
dlg.DefaultExt=".txt";
if(dlg.ShowDialog() == DialogResult.OK)
{
StreamReader objReader = newStreamReader(dlg.FileName);
textBox1.Text =objReader.ReadToEnd();
objReader.Close();
}
}
const int LCMAP_SIMPLIFIED_CHINESE =0x02000000;
const int LCMAP_TRADITIONAL_CHINESE =0x04000000;
enum ConvertType
{
Simplified,
Traditional
}
private Encoding gb2312 =Encoding.GetEncoding(936);
private void SCTCConvert(ConvertType c)
{
byte[]source = gb2312.GetBytes(textBox1.Text);
byte[]dest = new byte[source.Length];
switch(c)
{
caseConvertType.Simplified:
{
LCMapString(0x0804, LCMAP_SIMPLIFIED_CHINESE, source, -1, dest,source.Length);
break;
}
caseConvertType.Traditional:
{
LCMapString(0x0804, LCMAP_TRADITIONAL_CHINESE, source, -1, dest,source.Length);
break;
}
}
textBox1.Text = gb2312.GetString(dest);
}
private void button2_Click(object sender,EventArgs e)
{
SCTCConvert(ConvertType.Simplified);
}
private void button3_Click(object sender,EventArgs e)
{
SCTCConvert(ConvertType.Traditional);
}
[DllImport("kernel32.dll", EntryPoint ="LCMapStringA")]
public static extern int LCMapString(int Locale,int dwMapFlags, byte[] lpSrcStr, int cchSrc, byte[] lpDestStr, intcchDest);
}
}