如何将表单引用导出到另一个类以便重用?

时间:2016-11-29 08:46:23

标签: vb.net class

我有这个代码。我使用它来移动没有窗口栏的窗口。

' FUNCTIONS FOR WINDOW MOVEMENT    ------------------------------------------------------------------------

' Left mouse button pressed
Private Sub Login_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
    If e.Button = sender.MouseButtons.Left Then
        ' Get the new position
        mouseOffset = New Point(-e.X, -e.Y)
        ' Set that left button is pressed
        isMouseDown = True
    End If
End Sub

' MouseMove used to check if mouse cursor is moving
Private Sub Login_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
    If isMouseDown Then
        Dim mousePos As Point = Control.MousePosition
        ' Get the new form position
        mousePos.Offset(mouseOffset.X, mouseOffset.Y)
        Me.Location = mousePos
    End If
End Sub

' Left mouse button released, form should stop moving
Private Sub Login_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp
    If e.Button = sender.MouseButtons.Left Then
        isMouseDown = False
    End If
End Sub

如何将此代码导出到外部类以便以其他形式重复使用?

我有这个问题,因为我想在我的应用中的每个表单中重复使用它。我不能这样做,因为当我将Me.form作为参数传递时,我收到错误。

1 个答案:

答案 0 :(得分:0)

与Esko在评论中已经提到的一样,创建一个继承自white的基础表单类,并在那里定义鼠标事件处理程序:

Windows.Form

(确保Public MustInherit Class BaseForm Inherits System.Windows.Forms.Form Private mouseOffset As Point Private isMouseDown As Boolean Private Sub Login_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown ' ... End Sub ' MouseMove used to check if mouse cursor is moving Private Sub Login_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove '... End Sub ' Left mouse button released, form should stop moving Private Sub Login_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp '... End Sub End Class 是其自己文件中唯一的类。)

在表单的BaseForm文件中(例如Form1),从

更改继承

Designer.vb

Partial Class Form1 Inherits System.Windows.Forms.Form