
本站地址:http://www.bajiao123.com

Delphi下实现中文输入
在平时的计算机操作中,中文输入是不可避免的。使用者可能喜欢不同的中文输入法(Input
Method Editor,简称IME),因此,必须经常点击任务栏中的中文图标或用CTRL+Space,CTRL+Shift热键切换,初学者用起来很不方便。针对这一问题,在开发软件时,可以在程序中设置用户喜欢的中文输入法,方便用户的使用。Delphi中只有少数控件如TEdit支持IME,而且该功能不强,不能在运行时更改输入法。
笔者通过实践和摸索,查找了相关的IME资料,利用了WindowsAPI函数,实现了IME的功能。
常用函数有:
API函数:BOOLImmSimulateHotKey(HWNDhWnd,DWORDdwHotKeyID);//模拟热键,其中hWnd为程序窗口的句柄,dwHotHKeyID为模拟的热键,若成功则返回True
HKL GetKeyboardLayout(DWORDdwLayout);//获得当前键盘状态
BOOL ImmIsIME(HKLhKL);//判断当前是否处于中文输入状态,若是则返回True
自定义函数有:
打开相应输入法:OpenIme(imename:string),例OpenIme("全拼输入法");
关闭中文输入法:CloseIme;
以下是一个简单的例子。
使用时uses中加上imm。
具体的实现方法及源代码如下:
unit Unit1;
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;
procedure FormShow(Sender:TObject);
procedure OpenIme(imename:string);
procedure closeIme;
procedure ComboBox1Change(Sender:TObject);
procedure BitBtn1Click(Sender:TObject);
procedure BitBtn2Click(Sender:TObject);
procedure BitBtn3Click(Sender:TObject);
private
{Private declarations}
public
{Public declarations}
end;
var
Form1:TForm1;
implementation
{$R*.DFM}
procedure TForm1.FormShow(Sender:TObject);
var
j:integer;
begin
for j:=0 to screen.imes.count -1 do
begin
ComBoBox1.Items.Add(screen.Imes.strings[j]);
//获取系统中已安装的中文输入法
end;
end;
procedure Tform1.OpenIme(imename:string);
var
I:integer;
myhkl:hkl;
begin
if ImeName'' then
begin
if Screen.Imes.Count0 then
begin
I:=screen.Imes.indexof(imename);
if I>=0 then
myhkl:=hkl(screen.Imes.objects[i]);
activatekeyboardlayout(myhkl,KLF_ACTIVATE);
//设置相应的输入法
end;
end;
end;
procedure TForm1.closeime;
var
myhkl:hkl;
begin
myhkl:=GetKeyBoardLayOut(0);
if ImmIsIME(myhkl) then
//判断是否在中文状态,若是则关闭它
immsimulateHotkey(handle,IME_CHotKey_IME_NonIME_Toggle);
end;
procedure TForm1.ComboBox1Change(Sender:TObject);
begin
OpenIme(ComboBox1.Text);
end;
procedure TForm1.BitBtn1Click(Sender:TObject);
begin
immsimulateHotkey(handle,IME_CHotKey_shape_Toggle);
//切换半角和全角模式
end;
procedure TForm1.BitBtn2Click(Sender:TObject);
begin
immsimulateHotkey(handle,IME_CHotKey_symbol_Toggle);
//切换中文标点模式和英文标点模式
end;
procedure TForm1.BitBtn3Click(Sender:TObject);
begin
closeime;
end;
end.
本程序在Delphi3.0/4.0下通过。
本站地址:http://www.bajiao123.com

