我以日语输入法为例,但它在使用输入法输入的其他语言中可能是相同的。
当用户使用输入法在文本框中键入文本时,将激发KeyDown和KeyUp事件。但是,在用户使用Enter键验证输入法中的输入之前,TextBox.Text属性不会返回键入的文本。
例如,如果用户输入5次keydown,然后验证,我将得到5个keydown/keyup事件,每次TextBox.Text返回"“(空字符串),最后我将得到enter键的keydown/keyup,TextBox.Text将直接变为"あああああ”。
在用户最后验证之前,如何在用户输入时获取用户输入?
(我知道如何使用javascript在网页上的字段中执行此操作,因此这在C#中一定是可行的!)
发布于 2010-07-21 09:10:29
您可以使用它来获取当前的组合。这将适用于任何合成状态,以及日语、中文和韩语。我只在Windows7上测试过,所以不确定它是否能在其他版本的Windows上运行。
至于事情是一样的,那么,事情实际上在三者之间是可怕的不同。
using System.Text;
using System;
using System.Runtime.InteropServices;
namespace Whatever {
public class GetComposition {
[DllImport("imm32.dll")]
public static extern IntPtr ImmGetContext(IntPtr hWnd);
[DllImport("Imm32.dll")]
public static extern bool ImmReleaseContext(IntPtr hWnd, IntPtr hIMC);
[DllImport("Imm32.dll", CharSet = CharSet.Unicode)]
private static extern int ImmGetCompositionStringW(IntPtr hIMC, int dwIndex, byte[] lpBuf, int dwBufLen);
private const int GCS_COMPSTR = 8;
/// IntPtr handle is the handle to the textbox
public string CurrentCompStr(IntPtr handle) {
int readType = GCS_COMPSTR;
IntPtr hIMC = ImmGetContext(handle);
try {
int strLen = ImmGetCompositionStringW(hIMC, readType, null, 0);
if (strLen > 0) {
byte[] buffer = new byte[strLen];
ImmGetCompositionStringW(hIMC, readType, buffer, strLen);
return Encoding.Unicode.GetString(buffer);
} else {
return string.Empty;
}
} finally {
ImmReleaseContext(handle, hIMC);
}
}
}
}我见过的其他实现使用了StringBuilder,但使用字节数组要好得多,因为SB通常也会包含一些垃圾。字节数组采用UTF16编码。
通常,只要收到"WM_IME_COMPOSITION“消息,您就会像Dian所说的那样调用GetComposition。
在调用ImmGetContext之后调用ImmReleaseContext非常重要,这就是为什么它在finally块中的原因。
https://stackoverflow.com/questions/2392606
复制相似问题