中的按键事件——移动图片框

中的按键事件——移动图片框

本文介绍了C#中的按键事件——移动图片框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过按键事件上下移动 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.

我建议改用托管 PictureBoxformKeyDown 并使用完全相同的代码:

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#中的按键事件——移动图片框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 10:10