C#:调用API实现简繁转换

C#:调用API实现简繁转换



知识要点:
  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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值