有两种方式可切换输入法
1,模拟按键切换,一般我们在输入时是按"Ctrl+空格"键切换的,因此,可用sendkeys "^ "模拟按键达到切换输入法的目的,但这种方法的缺点是不能明确指定,是否切换为中文起决于当前的输入法状态,如果当前是中文,发这个命令后就切换成英文了。
2,强制指定中英文输入法。这个要用api首先获取系统里所有输入法,然后根据输入法属性判断是英文还是中文,这样需要英文输入时可自动切换到英文,需要中文时自动切换到中文,代码量稍微大些。
新建一个项目,窗口里放一个text控件、两个command控件,拷贝下述代码运行可见到上述切换输入法的效果(均在VB6、XP下调试通过):
Private Declare Function ImmIsIME Lib "imm32.dll" (ByVal hkl As Long) As Long
Private Declare Function ActivateKeyboardLayout Lib "user32" (ByVal hkl As Long, ByVal Flags As Long) As Long
Private Declare Function GetKeyboardLayoutList Lib "user32" (ByVal nBuff As Long, lpList As Long) As Long
Private Sub Command1_Click()
Dim i As Long, j As Long, hk(30) As Long
'强行切换为中文,如有需要还可以指定哪一种中文输入如:五笔、搜狗、智能ABC等
j = GetKeyboardLayoutList(30, hk(0))
For i = 0 To j - 1
If ImmIsIME(hk(i)) = 1 Then
ActivateKeyboardLayout hk(i), 0 '强制切换为中文输入法
Exit For
End If
Next
End Sub
Private Sub Command2_Click()
Dim i As Long, j As Long, hk(30) As Long
'强行切换为英文
j = GetKeyboardLayoutList(30, hk(0))
For i = 0 To j - 1
If ImmIsIME(hk(i)) = 0 Then
ActivateKeyboardLayout hk(i), 0 '强制切换为英文输入法
Exit For
End If
Next
End Sub
Private Sub Text1_Click()
'模拟按“Ctrl+空格”键,但不能明确指定中英文输入
SendKeys "^ "
End Sub