0

我知道PictureBox没有KeyDown事件,但我真的想捕获该事件。我使用的是表单的 KeyDown 事件,但是当小部件太多时会出现问题,所以我别无选择,只能将关键事件附在 PictureBox 中。在文档中,它说PreviewKeyDown用于在焦点位于 PictureBox 时捕获关键事件。我已经尝试通过使用MouseEnter将焦点设置在小部件上来做到这一点,但它只是不监听关键事件。

using System;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void pictureBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.H:
                    MessageBox.Show("Pressed button");
                    break;
            }
        }

        private void pictureBox1_MouseEnter(object sender, EventArgs e)
        {
            Focus();
        }

        private void pictureBox1_MouseLeave(object sender, EventArgs e)
        {
            ActiveControl = null;
        }
    }
}

我究竟做错了什么?

4

1 回答 1

1

您将重点放在 FORM 上,而不是 PictureBox 上。

改变:

private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
    Focus();
}

至:

private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
    pictureBox1.Focus();
}
于 2020-10-10T14:27:34.313 回答