gpt4 book ai didi

c# - 如何在 C# 中将所有 KeyPress 事件作为 UserControl 获取?

转载 作者:行者123 更新时间:2023-11-30 17:48:33 24 4
gpt4 key购买 nike

我已经阅读了很多关于按键事件的文章,但我不知道如何获取它们。我知道只有当前具有键盘焦点的控件才能获得新闻事件。但是我怎样才能确保我的用户控件拥有它呢?

没有运气就试过了:

public partial class Editor : UserControl

this.SetStyle(ControlStyles.Selectable, true);
this.TabStop = true;
...
//take focus on click
protected override void OnMouseDown(MouseEventArgs e)
{
this.Focus();
base.OnMouseDown(e);
}
...
protected override bool IsInputKey(Keys keyData)
{
return true;
}

还有这个:

//register global keyboard event handlers
private void Editor_ParentChanged(object sender, EventArgs e)
{
if (TopLevelControl is Form)
{
(TopLevelControl as Form).KeyPreview = true;
TopLevelControl.KeyDown += FCanvas_KeyDown;
TopLevelControl.KeyUp += FCanvas_KeyUp;
TopLevelControl.KeyPress += FCanvas_KeyPress;
}
}

后者给了我按键按下和按下事件,但仍然没有按键。当我的控件从 UserControl 继承时,是否有任何其他方法可以用来获取每个向下/向上/按下事件?

编辑:因为有一条评论链接了另一个 SO 问题:重要的是我也得到了 KeyPress 事件,因为无论使用哪种语言,它都会在每个键盘上发送正确的字符。这对于文本写作很重要。如果你只得到单独的键,你必须自己将它们处理成正确的字符。但也许有一种方便的方法可以将按下的键转换为本地化字符?

最佳答案

  • 将父表单(包含用户控件)的 KeyPreview 属性设置为 true
  • 向您的父表单添加一个新的 KeyPress 事件

设置父表单按键事件以将事件转发给您的用户控件:

private void parentForm_KeyPress(object sender, KeyPressEventArgs e)
{
// Forward the sender and arguments to your usercontrol's method
this.yourUserControl.yourUserControl_KeyPress(sender, e);
}

yourUserControl1_KeyPress 方法替换为您自己的方法,您希望在每次用户按下按钮(按下然后释放按钮)时运行该方法。

您还可以为您的用户控件创建一个新的 KeyPress 处理程序,并将发送者和 KeyPressEventArgs 对象转发到那里,如本例所示。

关于c# - 如何在 C# 中将所有 KeyPress 事件作为 UserControl 获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22782753/

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