将表单发送到 DLL 文件中声明的子



我正在尝试(最终)创建我自己的DLL文件到一些代码,我将在新项目中不断使用,我正在使用Visual Basic 2010

我正确创建了 DLL,但我遇到了一个子代码Me.Handle

的问题

我不知道如何将"我"发送给我的子

这是我的子(来自msdn中的一个例子)

Sub Start_Detection()
    Dim di As New DEV_BROADCAST_DEVICEINTERFACE
    di.dbcc_size = CUInt(Marshal.SizeOf(GetType(DEV_BROADCAST_DEVICEINTERFACE)))
    di.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE
    di.dbcc_reserved = 0
    di.dbcc_classguid = Guid.Parse("{88BAE032-5A81-49f0-BC3D-A4FF138216D6}")
    di.dbcc_name = Nothing
    hDevNotify = RegisterDeviceNotification(Me.Handle, di, DEVICE_NOTIFY_WINDOW_HANDLE)

End Sub

当我把它放在DLL中时,我不知道如何发送Me,因为在DLL项目中说"我"不是我的DLL项目的成员。

如果我将 sub 声明为 Sub Start_Detection(ByRef Form)Sub Start_Detection(ByVal Form) DLL 项目工作正常,但是当我从 Windows 表单项目中调用它时,会发生"空引用异常"。

在 Visual Basic 2010 中无法将表单作为参数发送吗?

谢谢!


编辑:我以这种方式调用潜艇

   Private Sub Frm_Config_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        MyDLL.Start_Detection(Me)
    End Sub

您可能还需要考虑对参数使用以下命名约定

Sub Start_Detection (ByVal sender As System.Object)

Sub Start_Detection (ByVal handle As IntPtr)

调用该方法时,将句柄值传递给 Class 方法

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    If Me.IsHandleCreated Then
        RecieveHandle.Start_Detection(Me.Handle)
    End If
End Sub

然后,一旦进入类模块,您可以执行一个常见的技巧来确认已提供变量,并且不要通过"Me"(VB)或"This"(C#)变量传递对整个表单的引用。

Public Class RecieveHandle
Public Shared Sub Start_Detection(ByVal sender As System.Object)
    If sender Is Nothing Then
        Throw New ArgumentException("Method requires sender parameter to be supplied")
    End If
    If Not TypeOf (sender) Is IntPtr Then
        Throw New ArgumentException("Method requires a valid pointer (handle) to the form.")
    End If
    Dim myFormHandle As IntPtr = CType(sender, IntPtr)
    Debug.Print(myFormHandle.ToInt64.ToString)
End Sub
End Class

Me属于表单而不是 DLL。如果你通过了IntPtr,你会没事的。

Sub Start_Detection(ptr As IntPtr)
 Dim di As New DEV_BROADCAST_DEVICEINTERFACE
 di.dbcc_size = CUInt(Marshal.SizeOf(GetType(DEV_BROADCAST_DEVICEINTERFACE)))
 di.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE
 di.dbcc_reserved = 0
 di.dbcc_classguid = Guid.Parse("{88BAE032-5A81-49f0-BC3D-A4FF138216D6}")
 di.dbcc_name = Nothing
 hDevNotify = RegisterDeviceNotification(ptr, di, DEVICE_NOTIFY_WINDOW_HANDLE)
End Sub

用法:

Start_Detection(Me.Handle)

最新更新