c#-使用箭头键移动PictureBox-处理PictureBox中的键盘事件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c#-使用箭头键移动PictureBox-处理PictureBox中的键盘事件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1766字,纯文字阅读大概需要3分钟。
内容图文
![c#-使用箭头键移动PictureBox-处理PictureBox中的键盘事件](/upload/InfoBanner/zyjiaocheng/668/c3b9fb5551b3475bafa7f9fab3008e94.jpg)
我有一个PictureBox,可在其中使用以下代码移动对象.我需要在表单中添加一些按钮,但是,当我启动程序时,箭头键会在按钮中导航,而不是在输入按键中导航.我已经尝试了很多
像Form.Load()上的PictureBox.Focus()和PictureBox.Select()之类的方法,并在此答案here上完全禁用箭头键导航,但我的对象将不再移动.
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控件是不可选择的,因此无法处理键盘事件.要解决此问题,您首先应该使控件成为可选择的:
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;
}
}
内容总结
以上是互联网集市为您收集整理的c#-使用箭头键移动PictureBox-处理PictureBox中的键盘事件全部内容,希望文章能够帮你解决c#-使用箭头键移动PictureBox-处理PictureBox中的键盘事件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。