如何使用带有箭头键的列表框移动图片框?

每件事都没关系form1 + picturebox1我可以使用下面的代码:

public Form1() { InitializeComponent(); KeyDown += new KeyEventHandler(Form1_KeyDown); } private void Form1_KeyDown(object sender, KeyEventArgs e) { int x = pictureBox1.Location.X; int y = pictureBox1.Location.Y; if (e.KeyCode == Keys.Right) x += 5; else if (e.KeyCode == Keys.Left) x -= 5; else if (e.KeyCode == Keys.Up) y -= 5; else if (e.KeyCode == Keys.Down) y += 5; pictureBox1.Location = new Point(x, y); } 

但; 如果我添加列表框来写位置图片框,我不能用箭头键移动图片框我怎么能这样做?

Probalby你的列表框得到的焦点不是forms,你可能必须听listboxs keydown-event。

编辑:

使用这个可聚焦的PictureBoxEx并收听它的previewkeydown-event:

 public class PictureBoxEx : PictureBox { public PictureBoxEx() { this.SetStyle(ControlStyles.Selectable, true); } protected override void OnClick(EventArgs e) { this.Focus(); base.OnClick(e); } } 

编辑:

或使用以下内容。 使用此function,您无需在窗体中移动控件,只需在控件中移动图像即可。

 public class PictureBoxEx : Control { public PictureBoxEx() { this.SetStyle(ControlStyles.Selectable | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true); } protected override void OnClick(EventArgs e) { this.Select(); base.OnClick(e); } private Image _Image; public Image Image { get { return _Image; } set { _Image = value; this.Invalidate(); } } private Point _ImageLocation = new Point(0,0); public Point ImageLocation { get { return _ImageLocation; } set { _ImageLocation = value; this.Invalidate(); } } private int _ImageLocationLeft = 0; public int ImageLocationLeft { get { return _ImageLocationLeft; } set { _ImageLocationLeft = value; ImageLocation = new Point(value, ImageLocationTop); } } private int _ImageLocationTop = 0; public int ImageLocationTop { get { return _ImageLocationTop; } set { _ImageLocationTop = value; ImageLocation = new Point(ImageLocationLeft, value); } } protected override void OnPaint(PaintEventArgs pe) { if (Image != null) { pe.Graphics.DrawImage(Image, ImageLocation); } base.OnPaint(pe); } protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e) { if (e.KeyData == Keys.Up || e.KeyData == Keys.Down || e.KeyData == Keys.Left || e.KeyData == Keys.Right) e.IsInputKey = true; base.OnPreviewKeyDown(e); } } 

您需要Invalidate将重绘您的UI; 为了查看您所做的更改。

您可以选择使用重载Invalidate(Region region)重绘某些区域,也可以通过执行Control.Invalidate()来使整个控件无效。

尝试addign: this.Invalidate(); 在你创建了新的Point

您还可以使用Refresh() ,它将使窗口无效并强制控件重绘。

这是一篇关于“如何:处理表单级别的键盘输入”的MSDN文章,您可能希望阅读该文章并将其与当前代码进行比较。 您可能希望将KeyDown更改为KeyPress。 而且正如我在评论中所说的,它确实可以在不强制使用Invalidate()Refresh()重绘表单的情况下工作。