【问题标题】:How to get all KeyPress events as a UserControl in C#?如何在 C# 中将所有 KeyPress 事件作为 UserControl 获取?
【发布时间】:2014-05-12 01:00:48
【问题描述】:

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

尝试了这个没有运气:

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?
  • 是的,参见第二个代码示例,第 6 行...
  • 不,您链接的解决方案是针对按键向下/向上事件。我需要的是按键,因为按键事件为每种键盘/语言发送正确的字符,而不是不同的键。如果您将其用于文本写作等,这很重要......
  • 用户控件不是为此而生的,它是其他控件的容器,其中一个获得焦点。如果您没有,则不应从 UserControl 派生,而应从 Control 派生。

标签: c# .net winforms keyboard


【解决方案1】:
  • 将父窗体(包含用户控件)的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 对象,如本例所示。

【讨论】:

    【解决方案2】:

    你能附加到表单事件吗?

    Private Sub MyControl_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim f = Me.FindForm
        If Not f.KeyPreview Then Throw New Exception("Form requires has Keypreview enabled")
        AddHandler f.KeyUp, Sub(sender2 As Object, e2 As KeyEventArgs)
    
                            End Sub
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2011-01-09
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多