VB.Net使可拖动的控件不在表单之外

时间:2015-08-05 13:08:04

标签: vb.net

我有一个可以使用下面的代码拖动的自定义控件,但问题是我可以将控件移出窗体。

    Private Sub ObjCan_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove

    If e.Button = Windows.Forms.MouseButtons.Left Then

        Me.Location = New Point(FormGame.PointToClient(MousePosition).X - 16, FormGame.PointToClient(MousePosition).Y - 16)

    End If

End Sub

1 个答案:

答案 0 :(得分:0)

设置Cursor.Clip以限制鼠标移动:

  

获取或设置表示剪切矩形的边界   光标。允许剪切的光标仅在其剪辑内移动   矩形。

这是一个标签的快速示例。请注意,如果您将Label移动到另一个容器(如Panel)中,代码仍然有效,而Label将被限制在Panel边界中:

Public Class Form1

    Private PrevClip As Rectangle

    Private Sub Label1_MouseDown(sender As Object, e As MouseEventArgs) Handles Label1.MouseDown
        PrevClip = Cursor.Clip
        Dim ctl As Control = DirectCast(sender, Control)
        Dim ctlContainer As Control = ctl.Parent
        Cursor.Clip = ctlContainer.RectangleToScreen(New Rectangle(0, 0, ctlContainer.ClientSize.Width - ctl.Width, ctlContainer.ClientSize.Height - ctl.Height))
    End Sub

    Private Sub Label1_MouseMove(sender As Object, e As MouseEventArgs) Handles Label1.MouseMove
        If e.Button = MouseButtons.Left Then
            Dim ctl As Control = DirectCast(sender, Control)
            Dim ctlContainer As Control = ctl.Parent
            ctl.Location = ctlContainer.PointToClient(Cursor.Position)
        End If
    End Sub

    Private Sub Label1_MouseUp(sender As Object, e As MouseEventArgs) Handles Label1.MouseUp
        Cursor.Clip = PrevClip
    End Sub

End Class