如何将图片框与列表框箭头键? [英] How to move picturebox with arrow keys with listbox?
问题描述
每个事情是确定的Form1中+ picturebox1我可以用很好跌破codeS:
Every things is ok form1+picturebox1 i can use good below codes:
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);
}
但; 如果我添加列表框编写位置PictureBox的,我不能移动图片框与箭头键我怎么能做到这一点?
BUT; if i add listbox to write position picturebox, i can not move picturebox with arrow keys how can i do that?
推荐答案
Probalby您的列表框获得焦点的不是形式,你可能要听的listboxs KEYDOWN事件。
Probalby your listbox gets the focus an not the form, you probably have to listen the listboxs keydown-event.
编辑:
使用这种可聚焦PictureBoxEx,听其previewkeydown事件:
Use this focusable PictureBoxEx and listen to its previewkeydown-event :
public class PictureBoxEx : PictureBox
{
public PictureBoxEx()
{
this.SetStyle(ControlStyles.Selectable, true);
}
protected override void OnClick(EventArgs e)
{
this.Focus();
base.OnClick(e);
}
}
编辑:
或使用以下。有了这个,你不必在移动形式的控制,而只是将图像的控制范围之内。
Or use the following. with this you don't have to move a control in the form, but just move the image within the control.
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);
}
}
这篇关于如何将图片框与列表框箭头键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!