如何在vba中用api函数切换输入法?

要切换输入法,首先要电脑中得安装有该输入法。

api函数LoadKeyboardLayout可以将指定的输入法装载进指定的进程或线程。

LoadKeyboardLayout函数的语法如下:

HKL LoadKeyboardLayoutW(
  LPCWSTR pwszKLID,
  UINT    Flags
);

其中pwszKLID参数在MSDN的官方解释如下:

The name of the input locale identifier to load. This name is a string composed of the hexadecimal value of the Language Identifier (low word) and a device identifier (high word). For example, U.S. English has a language identifier of 0x0409, so the primary U.S. English layout is named "00000409". Variants of U.S. English layout (such as the Dvorak layout) are named "00010409", "00020409", and so on.

pwszKLID参数为input locale identifier的名称。

如何在vba中获取到GetKeyboardLayoutName返回的键盘布局名称?一文中我们介绍了可以通过查找注册表的形式来获取对应的input locale identifier的名称。

比如在本人电脑上搜狗拼音输入法的input locale identifier的名称就是如下图所示:

Flags参数为加载的形式,具体可以看MSDN中的解释。

LoadKeyboardLayout函数加载成功后,将返回hkl,也就是加载成功的输入法的Input locale identifier。

当将指定的输入法加载进指定的进程或线程以后,还需要用api函数ActivateKeyboardLayout 将加载的输入法激活。

ActivateKeyboardLayout函数的语法如下:

HKL ActivateKeyboardLayout(
  HKL  hkl,
  UINT Flags
);

其中参数hkl表示Input locale identifier ,也就是LoadKeyboardLayout函数的返回值。Flags参数同上。

如果要在进程或线程中卸载指定的输入法,可以用UnloadKeyboardLayout函数。

以下的代码演示了如何加载并切换输入法为搜狗拼音输入法:

Declare Function LoadKeyboardLayout Lib "user32" Alias "LoadKeyboardLayoutW" (ByVal pwszKLID As Long, ByVal Flags As Long) As Long
Declare Function ActivateKeyboardLayout Lib "user32" (ByVal hkl As Long, ByVal Flags As Long) As Long
Declare Function UnloadKeyboardLayout Lib "user32" (ByVal hkl As Long) As Long
Const KLF_SETFORPROCESS = &H100
Sub QQ1722187970()
   Dim hkl As Long
   Dim str1 As String
   '搜狗拼音输入法的HKL名称
   str1 = "E0210804"
   '传递字符串变量的实际地址
   hkl = LoadKeyboardLayout(StrPtr(str1), KLF_SETFORPROCESS)
   '激活输入法
   ActivateKeyboardLayout hkl, KLF_SETFORPROCESS
   '卸载输入法
   UnloadKeyboardLayout hkl
End Sub
       

发表评论