简体   繁体   English

WinForms 自定义控件:为什么方向键不引发 OnKeyDown 事件?

[英]WinForms Custom Control: Why doesn't the arrow key raise the OnKeyDown event?

This is a dummy custom control.这是一个虚拟的自定义控件。 The entire source is at the bottom.整个来源在底部。 If I place the control on an empty form (no weird things like key preview, etc, just the default, empty, untouched form), and press some keys, weirdly, arrow keys do not raise OnKeyDown .如果我将控件放在一个空表单上(没有奇怪的东西,如键预览等,只是默认的、空的、未触及的表单),然后按一些键,奇怪的是,箭头键不会引发OnKeyDown Why?为什么?

If I keep pressing 'A'.如果我一直按“A”。

Process: A
Key down: A
Process: A
Key down: A
Process: A
Key down: A

If I keep pressing the Space bar.如果我一直按空格键。

Process: Space
Key down: Space
Process: Space
Key down: Space
Process: Space
Key down: Space
Process: Space

If I keep pressing the Down arrow.如果我一直按向下箭头。

Process: Down
Process: Down
Process: Down
Process: Down
Process: Down
Process: Down

Is overriding the ProcessCmdKey the only and best way to handle arrow key inputs?覆盖ProcessCmdKey是处理箭头键输入的唯一和最好的方法吗? I cannot use the OnKeyUp event, because it is raised only once, but users would keep pressing the arrow key to continuously scroll down, not just once when they release the arrow key.我不能使用OnKeyUp事件,因为它只引发一次,但用户会一直按箭头键以连续向下滚动,而不仅仅是在释放箭头键时一次。

public class MyControl : Control
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        Debug.WriteLine("Key down: " + e.KeyCode);
    }

    protected override void OnKeyUp(KeyEventArgs e)
    {
        base.OnKeyUp(e);
        Debug.WriteLine("Key up: " + e.KeyCode);
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        Debug.WriteLine("Process: " + keyData.ToString());
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

Overriding ProcessCmdKey I think is the right way to go here.我认为覆盖ProcessCmdKey是 go 的正确方法。 I can't fully explain why OnKeyDown isn't being called, but there's nothing particularly wrong with overriding ProcessCmdKey , and if it works, it works.我不能完全解释为什么OnKeyDown没有被调用,但是重写ProcessCmdKey并没有什么特别的错误,如果它有效,它就有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM