VB.NET 用 WndProc接收字符串消息
时间: 2023-11-27 09:49:10 浏览: 114
在VB.NET中,可以使用WndProc函数来接收字符串消息。下面是一个示例代码,可以接收自定义消息,并将消息的内容显示在Label控件上:
```vb
Public Class Form1
Inherits System.Windows.Forms.Form
Private Const WM_USER As Integer = &H400
Private Const WM_MYMESSAGE As Integer = WM_USER + 1
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = WM_MYMESSAGE Then
Dim msg As String = System.Runtime.InteropServices.Marshal.PtrToStringUni(m.LParam)
Me.Label1.Text = msg
End If
MyBase.WndProc(m)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim msg As String = "Hello World!"
Dim data As IntPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalUni(msg)
SendMessage(Me.Handle, WM_MYMESSAGE, IntPtr.Zero, data)
System.Runtime.InteropServices.Marshal.FreeHGlobal(data)
End Sub
Private Declare Function SendMessage Lib "user32" Alias "SendMessageW" _
(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
End Class
```
在这个示例中,我们定义了两个常量:`WM_USER`和`WM_MYMESSAGE`,分别表示用户自定义消息的起始值和我们自己定义的消息值。然后,我们在`WndProc`函数中判断消息是否是我们自己定义的消息,如果是,则通过`Marshal.PtrToStringUni`函数将消息内容转换为字符串,并将其显示在Label控件上。
在Button1的Click事件中,我们发送了一条自定义消息,消息的内容是"Hello World!"。我们首先使用`Marshal.StringToHGlobalUni`将字符串转换为指针,然后调用`SendMessage`函数发送消息。最后,我们使用`Marshal.FreeHGlobal`释放指针。
需要注意的是,WndProc函数必须在Form类中重载。此外,我们还需要使用`Declare`语句声明`SendMessage`函数。
阅读全文