1

这段代码我发现我用stackoverflow在vb.net中移动一个无边框的表单。我想为我项目的所有 10 种形式实现它,并且不想把它放在每个形式的代码中。有没有办法将此代码的单个实例用于所有表单?谢谢

Public Sub MoveForm_MouseDown(sender As Object, e As MouseEventArgs) Handles MyBase.MouseDown

    If e.Button = MouseButtons.Left Then
        MoveForm = True
        Me.Cursor = Cursors.NoMove2D
        MoveForm_MousePosition = e.Location
    End If

End Sub

Public Sub MoveForm_MouseMove(sender As Object, e As MouseEventArgs) Handles MyBase.MouseMove

    If MoveForm Then
        Me.Location = Me.Location + (e.Location - MoveForm_MousePosition)
    End If

End Sub

Public Sub MoveForm_MouseUp(sender As Object, e As MouseEventArgs) Handles MyBase.MouseUp

    If e.Button = MouseButtons.Left Then
        MoveForm = False
        Me.Cursor = Cursors.Default
    End If

End Sub
4

1 回答 1

2

创建一个派生类,表示无边界的可移动形式。让这个类从标准Form控件继承并添加您需要的任何附加功能。Form在构建表单时使用这个新类而不是标准。

Public Class MovableForm
    Inherits Form

Private MoveForm As Boolean
Private MoveForm_MousePosition As Point

Protected Overrides Sub OnMouseDown(e As MouseEventArgs)
    MyBase.OnMouseDown(e)

    If e.Button = MouseButtons.Left Then
        MoveForm = True
        Me.Cursor = Cursors.NoMove2D
        MoveForm_MousePosition = e.Location
    End If
End Sub

Protected Overrides Sub OnMouseMove(e As MouseEventArgs)
    MyBase.OnMouseMove(e)

    If MoveForm Then
        Me.Location += e.Location - MoveForm_MousePosition
    End If
End Sub

Protected Overrides Sub OnMouseUp(e As MouseEventArgs)
    MyBase.OnMouseUp(e)

    If e.Button = MouseButtons.Left Then
        MoveForm = False
        Me.Cursor = Cursors.Default
    End If
End Sub

End Class

然后使用它更改表单的设计器文件,如下所示:

Partial Class Form1
    Inherits BorderlessForm
于 2015-08-29T10:03:35.740 回答