【问题标题】:Capture key strokes from any child control at the parent level从父级的任何子控件捕获击键
【发布时间】:2016-06-15 22:08:04
【问题描述】:

我有一个包含许多子控件的 WinForm 控件。父控件永远不会有焦点。我想在父级别处理在子级别发生的某些击键组合。下面是我想要完成的一个简单示例。如果 ChildB(或 ChildB 中的某些控件)具有焦点,则按 Ctrl+A 应从视图中删除 ChildB 并添加 ChildA。

public partial class ParentControl : UserControl
{
    ChildControl ChildA = new ChildControl();
    ChildControl ChildB = new ChildControl();
    ChildControl ChildC = new ChildControl();

    public ParentControl()
    {
        InitializeComponent();
        Controls.Add(ChildA);
    }

    private void CapturedFromCildControl(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.A)
        {
            Controls.Clear();
            Controls.Add(ChildA);
        }
        if (e.Control && e.KeyCode == Keys.B)
        {
            Controls.Clear();
            Controls.Add(ChildB);
        }
        if (e.Control && e.KeyCode == Keys.C)
        {
            Controls.Clear();
            Controls.Add(ChildC);
        }
    }
}

【问题讨论】:

    标签: c# winforms events parent-child keystroke


    【解决方案1】:

    您可以让您的表单预览所有键。为此,您将表单 (!) 的属性 KeyPreview 设置为 true(默认值为 false)。当该属性为 true 时,所有子窗口的按键事件将首先通过 Form KeyEvent 处理程序。

    然后,您可以使用 ParentForm 引用从您的 ParentControl 订阅这些事件。 ParentControlLoad 事件应如下所示:

    private void ParentControl_Load(object sender, EventArgs e)
    {
        this.Controls.Add(new ChildControl1());
        this.ParentForm.KeyDown += CapturedFromCildControl;
    }
    

    在测试期间,您会注意到 sender 将是对表单的引用,而不是捕获按键的 ChildControl。这在您的用例中看起来不是问题,但最好提前知道。

    【讨论】:

      猜你喜欢
      • 2014-11-27
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多