0

我有从PictureBox控件派生的自定义控件。我想为它编写一个KeyDown事件,我已经编写了下面的代码,但我仍然无法使用它。如果我做错了什么或需要更多补充,请检查我的代码并指导我。我知道默认情况下 PictureBox 没有 KeyDown 事件,因此我正在尝试使用 KeyDown 事件制作自定义 Select-able PictureBox ...

    using System;
    using System.Linq;
    using System.Windows.Forms;

    namespace BenisImageDownloader
    {
        class SelectablePictureBox:PictureBox
        {
            public SelectablePictureBox()
            {
                this.SetStyle(ControlStyles.Selectable, true);
                this.TabStop = true;
            }

            protected override void OnMouseDown(MouseEventArgs e)
            {
                this.Focus();
                base.OnMouseDown(e);
            }

            protected override void OnKeyDown(KeyEventArgs e)
            {
                if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
                    e.Handled = true;
                base.OnKeyDown(e);
            }

            protected override bool IsInputKey(Keys keyData)
            {
                if (keyData == Keys.Up || keyData == Keys.Down) return true;
                if (keyData == Keys.Left || keyData == Keys.Right) return true;
                return base.IsInputKey(keyData);
            }

            protected override void OnEnter(EventArgs e)
            {
                this.Invalidate();
                base.OnEnter(e);
            }

            protected override void OnLeave(EventArgs e)
            {
                this.Invalidate();
                base.OnLeave(e);
            }

            protected override void OnPaint(PaintEventArgs pe)
            {
                base.OnPaint(pe);
                if (this.Focused)
                {
                    var rc = this.ClientRectangle;
                    rc.Inflate(-2, -2);
                    ControlPaint.DrawFocusRectangle(pe.Graphics, rc);
                }
            }
        }
    }

我是一名在 Windows Form Application v4.0 项目(不是 WPF)上工作的学生,我的论文要提交。

4

1 回答 1

1

您可以改写控件的ProcessCmdKey() 函数并捕获那里的按键。

(抱歉,我只有一个 VB 示例 - 但你会明白的):

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message,
                                           ByVal keyData As System.Windows.Forms.Keys) As Boolean

    'process key, return true for processed
    If (keyData And Keys.KeyCode) = Keys.KeyToCheck Then
        Return true
    End If

    Return MyBase.ProcessCmdKey(msg, keyData)

End Function
于 2012-11-17T09:57:20.780 回答