【问题标题】:Capture KeyUp event on form when child control has focus当子控件具有焦点时在表单上捕获 KeyUp 事件
【发布时间】:2009-06-19 14:36:40
【问题描述】:

我需要在我的表单中捕获 KeyUp 事件(以切换“全屏模式”)。这就是我正在做的事情:

protected override void OnKeyUp(KeyEventArgs e)
{
    base.OnKeyUp(e);

    if (e.KeyCode == Keys.F12) this.ToggleFullScreen();
}

private void ToggleFullScreen()
{
    // Snazzy code goes here           
}

这很好用,除非表单上的控件具有焦点。在这种情况下,我根本没有收到该事件(也尝试过 OnKeyDown - 也没有运气)。

我可以处理来自子控件的 KeyUp 事件,但窗体上的控件是动态生成的,并且可能有很多 - 每个都有很多自己的子控件。

有没有什么方法可以在不为屏幕上的每个控件生成事件处理程序的情况下做到这一点(我当然可以使用递归函数来做到这一点)?

【问题讨论】:

    标签: c# .net winforms event-handling


    【解决方案1】:

    将表单的 KeyPreview 设置为 true,您可以拦截 KeyUp 事件。

    在我的测试应用中,我做了这样的事情:

    this.KeyPreview = true;
    .
    .
    .
    
    
    private void button1_KeyUp(object sender, KeyEventArgs e)
    {
        Trace.WriteLine("button key up");
    }
    
    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        Trace.WriteLine("form key up");
        e.Handled = true;
    }
    

    它将转储表单跟踪行,向上处理键并且不会调用按钮处理程序。当然,您可以不处理事件(不执行 e.Handled = true),然后按钮处理程序也会被调用。

    【讨论】:

    • 正是我需要的!非常感谢!
    【解决方案2】:

    您是否尝试过在表单上全局处理事件?

    protected override bool ProcessCmdKey(ref Message msg, Keys e)
    {
        if (e.KeyCode == Keys.F12) 
        {
           this.ToggleFullScreen();
           return true; //marks command as handled
        }
    
        return base.ProcessCmdKey(ref msg, e); // Resend To Base Function
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 2015-01-01
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多