You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PictureBox无法移动求助:按键控制Kirby_Pic移动功能失效

解决PictureBox按键移动失效的问题

你的代码存在几个核心问题导致移动功能失效,以下是问题分析和修复方案:

问题点

  • 未处理KeyUp事件:松开W/A/S/D按键后,inputX/inputY会保持-1或1,导致控件持续移动且无法停止
  • 窗体未启用KeyPreview:如果焦点在其他控件(比如Leave_Btn)上,窗体的KeyDown事件不会被触发
  • 碰撞检测逻辑未绑定事件:Collision方法没有关联任何触发事件,永远不会执行
  • 多余导入:Imports System.CodeDom没有实际作用,可以移除

修复后的完整代码

Public Class Form1
    Private Sub Leave_Btn_Click(sender As Object, e As EventArgs) Handles Leave_Btn.Click
        End
    End Sub

    ' 碰撞检测:绑定到Timer Tick事件,每次移动后检测
    Private Sub Collision(sender As Object, e As EventArgs) Handles Timer1.Tick
        If Kirby_Pic.Bounds.IntersectsWith(BrontoBurt_Pic.Bounds) OrElse Kirby_Pic.Bounds.IntersectsWith(WaddleDee_Pic.Bounds) Then
            Kirby_Pic.Location = New Point(21, 97)
        End If
    End Sub

    Dim inputX, inputY As Integer
    Dim velocity As Integer = 4

    ' 窗体加载时启用KeyPreview,确保按键事件被窗体捕获
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.KeyPreview = True
        ' 确保Timer启动(如果设计器里没开的话)
        Timer1.Start()
    End Sub

    Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
        Select Case e.KeyCode
            Case Keys.W : inputY = -1
            Case Keys.S : inputY = 1
            Case Keys.A : inputX = -1
            Case Keys.D : inputX = 1
        End Select
    End Sub

    ' KeyUp事件:松开按键时重置方向变量
    Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) Handles MyBase.KeyUp
        Select Case e.KeyCode
            Case Keys.W, Keys.S : inputY = 0
            Case Keys.A, Keys.D : inputX = 0
        End Select
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        ' 计算新位置并限制在窗体可视范围内
        Dim newx = Kirby_Pic.Location.X + velocity * inputX
        newx = Math.Min(Math.Max(0, newx), Me.ClientSize.Width - Kirby_Pic.Width)
        Dim newy = Kirby_Pic.Location.Y + velocity * inputY
        newy = Math.Min(Math.Max(0, newy), Me.ClientSize.Height - Kirby_Pic.Height)
        Kirby_Pic.Location = New Point(newx, newy)
    End Sub
End Class

额外注意事项

  1. 确保设计器中Timer1的Enabled属性已设为True,或者通过代码Timer1.Start()启动
  2. 如果控件仍无法移动,检查Kirby_Pic的Enabled属性是否为True,且没有被其他控件遮挡

内容的提问来源于stack exchange,提问作者Jack Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 14:03:18