问题描述
我正在尝试通过按键事件上下移动 PictureBox(picUser).我是 C# 的新手,并且能够通过 VB 执行此操作.因此,我对以下代码的问题感到困惑:
I am attempting to move a PictureBox(picUser) up and down via the key press events. I am newer to C# and am able to do this via VB. As such I am confused as to what the problem is with the following code:
private void picUser_keyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
picUser.Top -= 10;
}
}
代码没有错误",只是图片框不动.
There is no "error" with the code, the picturebox just doesn't move.
推荐答案
PictureBox
没有 KeyDown
事件.它有一个 PreviewKeyDown
而需要 PictureBox
来获得焦点.
A PictureBox
has no KeyDown
event. It has a PreviewKeyDown
instead and requires the PictureBox
to have the focus.
我建议改用托管 PictureBox
的 form
的 KeyDown
并使用完全相同的代码:
I would suggest to use the KeyDown
of the form
that host the PictureBox
instead and use the same exact code:
public Form1()
{
InitializeComponent();
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
picUser.Top -= 10;
}
}
这篇关于C#中的按键事件——移动图片框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!