检测箭头键 - 的KeyDown整个窗口窗口、箭头键、KeyDown

2023-09-02 01:58:48 作者:A million years.[一眼万年]

我有一个WinForms表格(C#/。NET),它包含了一个图片,MenuStrip中,面板和两个Button控件。

I have a WinForms Form (C#/.Net) and it contains a PictureBox, MenuStrip, Panel and two Button controls.

我需要检测KeyDown事件的箭头键在整个窗口;也就是说,当窗口是在前台,无论哪个子控件中的一个具有焦点,我需要知道什么时候方向键是pssed $ P $,并执行一些code,当它发生。

I need to detect KeyDown event for the Arrow Keys for the whole window; i.e., when the window is in the foreground, regardless of which one of the child controls has the focus, I need to know when an arrow key is pressed and execute some code when it happens.

我不想去和附加的事件处理程序为每个控件。有没有更好的办法?我该怎么办呢?

I don't want to go and attach an event handler for each control. Is there a better way? How can I do it?

编辑:使用键preVIEW所建议的下面一个答案,我能够探测到其他按键。不能够检测到方向键。我能只检测箭头键时,在我的表格按钮被禁用。否则,他们采取了重点来回,不触发事件。我如何可以检测方向键与表单上的按钮?

Using KeyPreview as suggested by an answer below, I am able to detect other keys. Not able to detect arrow keys. I am able to detect arrow keys only when the buttons in my form are disabled. Or else, they take up focus back and forth and don't fire the event. How can I detect arrow keys with buttons on the form?

推荐答案

覆盖给ProcessCmdKey()方法来检测方向键。

Override the ProcessCmdKey() method to detect the arrow keys.

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
        if (keyData == Keys.Left) {
            Console.WriteLine("left");
            return true;
        }
        // etc..
        return base.ProcessCmdKey(ref msg, keyData);
    }