在编写代码时,经常要处理用户当前的输入法编辑器IME。如果不管用户的输入法,会给你的程序运行带来一些困扰,甚至会让系统崩溃。
比如,准备监测用户的键盘输入时,如果用户开启的中文输入法,则获取到的键盘值会完全不一样。而另一方面,需要用户输入中文时,就默认开启中文输入法,以提升用户使用体验。
废话少说,直接上代码!
uses WinApi.Windows, WinApi.Imm, FMX.Platform.Win, .....;//关闭或开启IME状态 {函数声明部分}function CloseIME : Boolean;function OpenIME : Boolean;implementation {函数实现部分}//关闭IME状态
function CloseIME : Boolean;
varhnd : HWND;imc : HIMC;
begin{$IFDEF MSWINDOWS} //delphi是跨平台开发语言,需要加上这个开关,告诉编译器在windows平台编译以下代码Result := False;hnd := WindowHandleToPlatForm(Screen.ActiveForm.Handle).Wnd;if hnd<>0 then beginimc := ImmGetContext(hnd);if imc<>0 then begintryif ImmGetOpenStatus(imc) then ImmSetOpenStatus(imc, False);Result := not ImmGetOpenStatus(imc);finallyImmReleaseContext(Hnd, imc);end;end;end;{$ENDIF}
end;//开启IME状态
function OpenIME : Boolean;
varhnd : HWND;imc : HIMC;
begin{$IFDEF MSWINDOWS}Result := False;hnd := WindowHandleToPlatForm(Screen.ActiveForm.Handle).Wnd;if hnd<>0 then beginimc := ImmGetContext(hnd);if imc<>0 then begintryif not ImmGetOpenStatus(imc) then ImmSetOpenStatus(imc, True);Result := ImmGetOpenStatus(imc);finallyImmReleaseContext(Hnd, imc);end;end;end;{$ENDIF}
end;