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

时间:2015-01-17 02:59:23

标签: 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

谢谢...

2 个答案:

答案 0 :(得分:1)

默认情况下,控件的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

答案 1 :(得分:0)

更新了解决方案

这是一种完成它的方法,以便在按住键的同时移动它。使用表单和按钮创建项目。

在Solution Explorer中右键单击Project并添加两个.NET References:

  • 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