我正在制作一个简单的程序,要求我能够选择一个图片框,并用鼠标拖动它将其移动到一个新的位置。这是我目前提出的所有相关代码。但是,当我运行该程序时,它会尝试移动到我想要的位置,然后它似乎恢复到之前的位置。
编辑:它在一个容器中。如果这是相关的。
变量
Dim startx As Integer
Dim starty As Integer
Dim endy As Integer
Dim endx As Integer
Dim finalx As Integer
Dim finaly As Integer
Dim mdown As Boolean
Dim valx As Boolean
Dim valy As Boolean
移动图片的代码
Private Sub picbox_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles picbox.MouseDown
startx = MousePosition.X
starty = MousePosition.Y
mdown = True
valx = False
valy = False
End Sub
Private Sub Main_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
End Sub
Private Sub picbox_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles picbox.MouseMove
'Check if mouse=down
If mdown = True Then
endx = (MousePosition.X - Me.Left)
endy = (MousePosition.Y - Me.Top)
If valy = False Then
starty = endy - sender.top
valy = True
End If
If valx = False Then
startx = endx - sender.left
valx = True
End If
sender.left = endx - startx
sender.top = endy - starty
End If
End Sub
Private Sub picbox_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles picbox.MouseUp
mdown = False
valx = False
valy = False
End Sub
答案 0 :(得分:2)
将其从容器中取出。这可能是什么给你带来了问题,因为你的代码对我来说非常合适。
答案 1 :(得分:1)
关闭Autosize
属性。
答案 2 :(得分:1)
转动AutoSize,确保关闭图片框的停靠并确保Anchor处于左上角
答案 3 :(得分:0)
这对我有用:
Private _isMoved As Boolean
Private _x As Integer
Private _y As Integer
Private Sub Control_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Control.MouseDown
_isMoved = True
_x = e.Location.X
_y = e.Location.Y
End Sub
Private Sub Control_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Control.MouseMove
If _isMoved Then
Control.Location = New Point(Control.Location.X + (e.Location.X - _x), Control.Location.Y + (e.Location.Y - _y))
End If
End Sub
Private Sub Control_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Control.MouseUp
_isMoved = False
End Sub