Delphi下编程实现中文输入


  BorlandDelphi以其 壮大的 性能及和高效的可 视化开发环境为 辽阔程序设计员所青睐 。尤其是它封装了WINDOWSAPI函数,能容易地利 用WINDOWS资源,大大加速了程序开发速度 。

  在平时的计算机操作中,中文输入是不可幸免的 。 使用者可能喜爱不同的中文输入法(inputmethodeditor,简称IME),这就只能 时常点击 使命栏中的中文图标或用CTRL+Space,CTRL+Shift热键切换,初学者用起来很不容易 。针对 这一问题, 可以在开发软件时,在程序中设置消费者喜爱的中文输入法,容易消费者的 使用 。Delphi 中惟独少数控件如TEdit 支撑IME,并且该 性能不强,不能在运行时更改输入法 。

  小编通过 实际和探索,搜索了 有关的IME 材料,利 用了WINDOWSAPI函数,实现了IME的 性能 。

  常用函数有:

API函数:BOOLImmSimulateHotKey

(HWNDhWnd,DWORDdwHotKeyID);// 模仿热键

其中Hwnd为程序窗口的句柄,dwHotHKeyID

为 模仿的热键,若 顺利则返回True

HKLGetKeyboardLayout(DWORDdwLayout);

// 获得目前键盘状态

 

BOOLImmIsIME(HKLhKL);

//推断目前是不是处于中文输入状态,若是则返回True

自定义函数:

打开相应输入法:OpenIme(imename:string),

例OpenIme(全拼输入法);

关闭中文输入法:CloseIme;

以下是一个 容易的例子,仅起参考作用 。

使用时uses中外加imm

具体的实现 步骤及源代码如下:

unitUnit1;

interface

uses

Windows,Messages,SysUtils,Classes,

  Graphics,Controls,Forms,Dialogs,

StdCtrls,Buttons,imm;

type

TForm1=class(TForm)

ComboBox1:TComboBox;

BitBtn1:TBitBtn;

BitBtn2:TBitBtn;

BitBtn3:TBitBtn;

procedureFormShow(Sender:TObject);

procedureOpenIme(imename:string);

procedurecloseIme;

procedureComboBox1Change(Sender:TObject);

procedureBitBtn1Click(Sender:TObject);

procedureBitBtn2Click(Sender:TObject);

procedureBitBtn3Click(Sender:TObject);

private

{Privatedeclarations}

public

{Publicdeclarations}

end;

var

Form1:TForm1;

implementation

{$R*.DFM}

procedureTForm1.FormShow(Sender:TObject);

var

j:integer;

begin

forj:=0toscreen.imes.count-1do

begin

ComBoBox1.Items.Add(screen.Imes.strings[j]);

  //猎取系统中已安装的中文输入法

end;

end;

procedureTform1.OpenIme(imename:string);

var

I:integer;

myhkl:hkl;

begin

ifImeName<>then

begin

ifScreen.Imes.Count<>0then

begin

I:=scr   .Imes.indexof(imename);

ifI>=0then

myhkl:=hkl(screen.Imes.objects[i]);

activatekeyboardlayout(myhkl,

  KLF_ACTIVATE);//设置相应的输入法

end;

end;

end;

procedureTForm1.closeime;

var

myhkl:hkl;

begin

myhkl:=GetKeyBoardLayOut(0);

ifImmIsIME(myhkl)then

 //推断是不是在中文状态,若是则关闭它

immsimulateHotkey(handle,

IME_CHotKey_IME_NonIME_Toggle);

end;

procedureTForm1.ComboBox1Change(Sender:TObject);

begin

OpenIme(ComboBox1.Text);

end;

procedureTForm1.BitBtn1Click(Sender:TObject);

begin

immsimulateHotkey(handle,

IME_CHotKey_shape_Toggle);//切换半角和全角模式

end;

procedureTForm1.BitBtn2Click(Sender:TObject);

begin

immsimulateHotkey(handle,

IME_CHotKey_symbol_Toggle);

  //切换中文标点模式和英文标点模式

end;

procedureTForm1.BitBtn3Click(Sender:TObject);

begin

closeime;

end;

end.