C# Winform 键盘按键 KeyDown 单次触发

当设置KeyDown 事件后,按下会持续触发该事件,目前只想触发一次,解决办法: public partial class MainWindow : Form { private HashSet<Keys> _keysPressed = new HashSet<Key

当设置KeyDown 事件后,按下会持续触发该事件,目前只想触发一次,解决办法:

    public partial class MainWindow : Form
    {
        private HashSet<Keys> _keysPressed = new HashSet<Keys>();    //添加
        Robot robot = new();

        public MainWindow()
        {
            InitializeComponent();
            KeyPreview = true;    //添加
        }

        private void MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            if (mainWindowPannel.Controls.Contains(robot) && !_keysPressed.Contains(e.KeyCode))
            {
                _keysPressed.Add(e.KeyCode);    //添加
                robot.Robot_KeyDown(sender, e);        //传递给用户控件
            }
        }

        private void MainWindow_KeyUp(object sender, KeyEventArgs e)
        {
            if (mainWindowPannel.Controls.Contains(robot) && _keysPressed.Contains(e.KeyCode))
            {
                _keysPressed.Remove(e.KeyCode);    //添加
                robot.Robot_KeyUp(sender, e);        //传递给用户控件
            }
        }
    }
}

LICENSED UNDER CC BY-NC-SA 4.0
Comment