使用箭头键移动PictureBox – 处理PictureBox中的键盘事件
我有一个PictureBox
,我使用下面的代码来移动我的对象。 我需要在表单中添加几个按钮,但是当我启动程序时,箭头键会导航按钮而不是我的输入按键。 我在Form.Load()
PictureBox.Select()
上尝试过很多像PictureBox.Focus()
和PictureBox.Select()
这样的Form.Load()
,并且在这里完全禁用箭头键导航,但是我的对象不再移动了。
private void UpdateScreen(object sender, EventArgs e) { if (Input.KeyPressed(Keys.Right) && Settings.direction != Direction.Left) { Settings.direction = Direction.Right; } else if (Input.KeyPressed(Keys.Left) && Settings.direction != Direction.Right) { Settings.direction = Direction.Left; } else if (Input.KeyPressed(Keys.Up) && Settings.direction != Direction.Down) { Settings.direction = Direction.Up; } else if (Input.KeyPressed(Keys.Down) && Settings.direction != Direction.Up) { Settings.direction = Direction.Down; } }
如何在不影响UpdateScreen()
代码的情况下禁用所有按钮的箭头键导航?
PictureBox
控件不Selectable
,因此无法处理Keyboard事件。 要解决此问题,您应首先使控件可选:
using System; using System.Windows.Forms; class SelectablePictureBox : PictureBox { public SelectablePictureBox() { SetStyle(ControlStyles.Selectable, true); SetStyle(ControlStyles.UserMouse, true); TabStop = true; } protected override void OnEnter(EventArgs e) { base.OnEnter(e); this.Invalidate(); } protected override void OnLeave(EventArgs e) { base.OnLeave(e); this.Invalidate(); } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); if (this.Focused) ControlPaint.DrawFocusRectangle(pe.Graphics, ClientRectangle); } }
然后你可以处理它的PreviewKeyDown
事件:
private void selectablePictureBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (e.KeyCode == Keys.Left) { e.IsInputKey = true; myPictureBox1.Left -= 10; } else if (e.KeyCode == Keys.Right) { e.IsInputKey = true; myPictureBox1.Left += 10; } }
- Marshal.PtrToStructure(以及返回)和字节顺序交换的通用解决方案
- C#是否具有“ThreadLocal”模拟(对于数据成员)到“ThreadStatic”属性?
- 获取DIV内的链接
- RegisterClientScriptBlock参数在实际场景中使用?
- 检查控件是否在Click EventHandler上有事件
- RadiobuttonFor用于Mvc Razor语法
- .Net CultureInfo Month Names返回一个额外的空字符串
- 将大型MFC应用程序迁移到WPF / .NET有哪些技巧?
- 考虑到使用Task.Run异步运行任何方法的能力,.Net Framework中的* Async方法的目的是什么?