提问人:andreat 提问时间:3/15/2023 更新时间:3/16/2023 访问量:29
从 OnKeyDown 调用 OnKeyPress
From OnKeyDown Call OnKeyPress
问:
由于某种原因,在我的环境 (CAD) 中,未调用按键。所以我需要从重写KeyDown事件中手动调用它。如何将KeyDown信息转换为字符以传递给KeyPress事件并正确管理有关修饰符,capslock,键盘布局,ecc的所有情况? 是否有网络框架或低级窗口函数可以为我执行此操作? 谢谢
答:
0赞
andreat
3/16/2023
#1
我是这样解决的:
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int ToUnicode(
uint virtualKeyCode,
uint scanCode,
byte[] keyboardState,
StringBuilder receivingBuffer,
int bufferSize,
uint flags
);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetKeyboardState(byte[] lpKeyState);
string GetCharsFromKeys(Keys keys)
{
var buf = new StringBuilder(256);
var keyboardState = new byte[256];
GetKeyboardState(keyboardState);
ToUnicode((uint)keys, 0, keyboardState, buf, 256, 0);
return buf.ToString();
}
private void txt_KeyDown(object sender, KeyEventArgs e)
{
string text = GetCharsFromKeys(e.KeyData);
if (!string.IsNullOrEmpty(text))
{
KeyPressEventArgs keyPressEventArgs = new KeyPressEventArgs(text[0]);
OnKeyPress(keyPressEventArgs);
}
}
所有键也使用修饰键、capslock、alt gr 等。在我的键盘上工作。
评论
KeyPress
e.SuppressKeyPress
OnKeyDown
true