检测箭头键 - 的KeyDown整个窗口 [英] Detect Arrow Key - KeyDown for the whole window

查看:243
本文介绍了检测箭头键 - 的KeyDown整个窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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);
    }

这篇关于检测箭头键 - 的KeyDown整个窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆