在winform中捕获上下左右键等控制键的按键事件

最近一直在做表单设计器,今天有一个需求就是:通过上下左右键来控制表单上的控件移动。
但是控件的KeyDown捕获不到上下左右键,KeyUp事件倒是可以捕获到,但你通过上下左右键移动控件位置,不能点一下才移动一下啊,太不人性了。上网找了半天发现了这么一个方法:

重写Control的ProcessDialogKey方法,此处以winform表单为例:

protected override bool ProcessDialogKey(Keys keyData)
        {
            Control control = this.GetFocusedControl();
            this.MoveControlByKeys(keyData, control);
            return base.ProcessDialogKey(keyData);
        }
        /// <summary>
        /// 根据keyData的值移动控件control
        /// </summary>
        /// <param name="keyData"></param>
        /// <param name="control"></param>
        private void MoveControlByKeys(Keys keyData, Control control)
        {
            if (keyData == Keys.Left)
            {
                if (control.Location.X > 0)
                {
                    control.Location = new Point(control.Location.X - 1, control.Location.Y);
                }
            }
            else if (keyData == Keys.Right)
            {
                control.Location = new Point(control.Location.X + 1, control.Location.Y);
            }
            else if (keyData == Keys.Up)
            {
                if (control.Location.Y > 0)
                {
                    control.Location = new Point(control.Location.X, control.Location.Y - 1);
                }
            }
            else if (keyData == Keys.Down)
            {
                control.Location = new Point(control.Location.X, control.Location.Y + 1);
            }
        }

        //API声明:获取当前焦点控件句柄    
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
        internal static extern IntPtr GetFocus();
        ///获取 当前拥有焦点的控件
        private Control GetFocusedControl()
        {
            Control focusedControl = null;
            // To get hold of the focused control:
            IntPtr focusedHandle = GetFocus();
            if (focusedHandle != IntPtr.Zero)
                //focusedControl = Control.FromHandle(focusedHandle);
                focusedControl = Control.FromChildHandle(focusedHandle);
            return focusedControl;
        }
在表单设计器中这个方法不起作用,不清楚为什么
于是还要寻找新的解决方案,但是发现了PreviewKeyDown事件,在表单设计器中,它可以获取到上下左右键,问题解决。

关于PreviewKeyDown部分内容可以参考: 点击打开链接

你可能感兴趣的:(事件,WinForm,捕获,键,上下左右)