2012-06-25 87 views
2

我正在研究一個簡單的程序,它需要我能夠選擇一個圖片框,並通過用鼠標拖動它將其移動到一個新的位置。這是我目前提出的所有相關代碼。但是,當我運行該程序時,它會嘗試移動到我想要的位置,然後它會恢復到之前的位置。如何通過單擊並用鼠標按住對象來移動元素?

編輯:它在一個容器中。如果這是任何相關性。

變量

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

想你的代碼用一個簡單的形式,只是一個圖片框。好消息是:它有效,壞消息是:我找不到你的錯誤。 – Steve

+0

我確實在佈局容器中有它。這可能與它有關嗎? – nick122

+0

這是一個winforms應用程序,對吧?你在哪種控制容器中擁有你的圖片盒?在我的測試中,沒有任何容器,直接在表單的客戶區域,一切都按預期工作。 – Steve

回答

2

刪除它從容器中。這可能是因爲你的代碼完全適合我,所以會給你帶來問題。

+0

聖潔的廢話,工作。任何想法爲什麼這給我的問題? – nick122

+0

取決於容器,但如果它是流動容器,如果有任何東西被停靠,那可能會導致問題。 – FreeSnow

1

關閉Autosize財產。

+0

它已經關閉 – nick122

+0

@ Nick122 - 無論是窗體,容器還是其他所有可見且可能涉及錨定的控件?容器是哪種類型? –

1

打開自動調整大小的,確保PictureBox的對接被關閉,並確保錨左上角

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 
相關問題