如何使用 VB.net 中的编码更改对象的位置 (x,y)?

How to change the Location (x,y) of the object by using coding in VB.net?

如果有和我一样的问题,我想说声抱歉。我试过搜索但我找不到它,所以..我希望没有其他类似的问题..

说到这里,我需要你的帮助来告诉我如何更改表单中对象的位置

我想做的是当我按下键盘上的左键时让 Button1 向左移动。但是我对如何设置对象的位置 (x,y) 有疑问

 Private Sub Button1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Button1.KeyPress
    If Asc(e.KeyChar) = Keys.Left Then

    End If
End Sub

谢谢...

更新解决方案

这里有一种实现方法,它可以在按住键的同时移动。使用窗体和按钮创建一个项目。

在解决方案资源管理器中右键单击项目并添加两个 .NET 引用:

  • PresentationCore
  • WindowsBase

这是代码。计时器将捕获按键事件并移动按钮:

Imports System.Windows.Input

Public Class Form1
    Private timex As New Timer

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        AddHandler timex.Tick, AddressOf myTickEvent
        timex.Enabled = True
        timex.Interval = 100
    End Sub
    Private Sub myTickEvent(sender As Object, e As EventArgs)
        If isKeyPressed(Key.Left) Then
            Me.Button1.Left -= 10
        End If
        If isKeyPressed(Key.Right) Then
            Me.Button1.Left += 10
        End If
        If isKeyPressed(Key.Up) Then
            Me.Button1.Top -= 10
        End If
        If isKeyPressed(Key.Down) Then
            Me.Button1.Top += 10
        End If
    End Sub
    Private Function isKeyPressed(ByRef keys As System.Windows.Input.Key)
        If (Windows.Input.Keyboard.GetKeyStates(keys) And Windows.Input.KeyStates.Down) > 0 Then
            Return True
        Else
            Return False
        End If
    End Function
End Class

默认情况下,箭头键不会被控件的 KeyPress、KeyDown 或 KeyUp 事件捕获。您可以通过在 PreviewKeyDown 事件中将 e.IsInputKey 设置为 True 使它们被 KeyDown 和 KeyUp 捕获。然后你可以通过改变它的 Left 属性 来横向移动按钮。以下假定按钮具有焦点。

Private Sub Button1_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) _
  Handles Button1.PreviewKeyDown
    If e.KeyCode = Keys.Left Or e.KeyCode = Keys.Right Then e.IsInputKey = True
End Sub

Private Sub Button1_KeyDown(sender As Object, e As KeyEventArgs) _
  Handles Button1.KeyDown
    Dim myButton As Button = CType(sender, Button)
    If e.KeyCode = Keys.Left Then myButton.Left -= 1
    If e.KeyCode = Keys.Right Then myButton.Left += 1
End Sub