4

我正在开发一个简单的程序,该程序要求我能够选择一个图片框并通过用鼠标拖动它来将其移动到新位置。这是我目前提出的所有相关代码。但是,当我运行程序时,它会尝试移动到我希望它去的地方,然后它似乎又回到了以前的位置。

编辑:它在一个容器中。如果这有任何相关性。

变量

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) 处理 picbox.MouseDown
        startx = MousePosition.X
        starty = MousePosition.Y
        mdown = 真
        valx = 假
        值 = 假
    结束子

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

4

4 回答 4

2

将其从容器中取出。这可能就是给您带来问题的原因,因为您的代码对我来说非常完美。

于 2012-06-25T20:28:06.673 回答
2

关闭Autosize属性。

于 2012-06-25T19:48:09.517 回答
2

这对我有用:

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
于 2017-02-18T15:35:02.073 回答
1

开启 AutoSize,确保图片框的停靠关闭,并确保 Anchor 位于左上角

于 2012-06-25T19:59:27.003 回答