如何使用键盘事件进行连续移动?

发布于 2025-02-10 11:19:25 字数 395 浏览 3 评论 0原文

当前,此代码运行良好并移动picturebox,但它总是将其移动一次,等待大约一秒钟,然后继续移动它。如何使运动继续前进而不是停下来?

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.A)
    {
        x = pictureBox1.Location.X;
        y = pictureBox1.Location.Y;
        if (pictureBox1.Location.X > 0)
        {
             pictureBox1.Location = new Point(x - 10, y);
        }
    }
}

Currently, this code runs fine, and moves the picturebox, but it always moves it once, waits about a second, and then continues to move it. How do I make the movement keep going instead of stopping for a second?

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.A)
    {
        x = pictureBox1.Location.X;
        y = pictureBox1.Location.Y;
        if (pictureBox1.Location.X > 0)
        {
             pictureBox1.Location = new Point(x - 10, y);
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

┼── 2025-02-17 11:19:25

实现此结果的一种方法是使用计时器,并在keydown事件上启用它,并在keyup事件上将其禁用。当movetimer.tick发生时(在这种情况下,每25毫秒左右),请通过向左移动“一次”来处理事件,直到释放键为止。

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        MoveTimer.Tick += (sender, e) =>
        {
            pictureBox1.Location = new Point(
                pictureBox1.Location.X - 10, 
                pictureBox1.Location.Y);
        };
    }
    Timer MoveTimer = new Timer { Interval = 25 };
    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        if(e.KeyData == Keys.A)
        {
            MoveTimer.Enabled = true;
        }
    }
    protected override void OnKeyUp(KeyEventArgs e)
    {
        base.OnKeyUp(e);
        MoveTimer.Enabled = false; // No need to check which key
    }
}

One way to achieve this outcome is to use a Timer and enable it on KeyDown event and disable it on KeyUp event. When MoveTimer.Tick occurs (in this case every 25 ms or so), handle the event by moving "once" to the left until the key is released.

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        MoveTimer.Tick += (sender, e) =>
        {
            pictureBox1.Location = new Point(
                pictureBox1.Location.X - 10, 
                pictureBox1.Location.Y);
        };
    }
    Timer MoveTimer = new Timer { Interval = 25 };
    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        if(e.KeyData == Keys.A)
        {
            MoveTimer.Enabled = true;
        }
    }
    protected override void OnKeyUp(KeyEventArgs e)
    {
        base.OnKeyUp(e);
        MoveTimer.Enabled = false; // No need to check which key
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文