gpt4 book ai didi

C# 和 IME - 获取当前输入文本

转载 作者:太空狗 更新时间:2023-10-29 23:04:23 25 4
gpt4 key购买 nike

我以日语 IME 为例,但在使用 IME 进行输入的其他语言中可能也是如此。

当用户使用 IME 在文本框中键入文本时,会触发 KeyDown 和 KeyUp 事件。但是,在用户使用 Enter 键验证 IME 中的输入之前,TextBox.Text 属性不会返回键入的文本。

因此,例如,如果用户输入 5 次 あ 然后验证,我将获得 5 次 keydown/keyup 事件,每次 TextBox.Text 返回“”(空字符串),最后我将获得 keydown/keyup对于回车键,TextBox.Text会直接变成“あああああ”。

如何在用户输入时,在用户最后验证之前获取用户输入?

(我知道如何在网页上的 <input> 字段上用 javascript 执行此操作,所以它在 C# 中一定是可能的!)

最佳答案

您可以使用它来获取当前合成。这适用于任何组合状态,适用于日语、中文和韩语。我只在 Windows 7 上测试过它,所以不确定它是否适用于其他版本的 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 编码。

通常,如 Dian 所说,只要收到“WM_IME_COMPOSITION”消息,您就会希望调用 GetComposition。

在调用 ImmGetContext 之后调用 ImmReleaseContext 非常重要,这就是它在 finally block 中的原因。

关于C# 和 IME - 获取当前输入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2392606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com