VB.NET 两个独立的exe互发消息
时间: 2023-08-18 13:06:05 浏览: 60
要实现两个独立的exe互发消息,可以使用Windows API中的SendMessage函数。
首先,在接收方的exe中,需要定义一个窗口并创建一个消息循环,等待来自发送方的消息。这可以通过使用Windows API中的CreateWindowEx和GetMessage函数来实现。
然后,在发送方的exe中,可以使用SendMessage函数向接收方的窗口发送消息。消息可以是任何自定义的格式,例如一个字符串或者一个结构体。
接收方的窗口过程可以解析接收到的消息,并执行相应的操作。例如,如果消息是一个字符串,可以在窗口中显示该字符串。
以下是一个简单的VB.NET示例,演示如何实现两个独立的exe互发消息:
```vb.net
' 发送方的代码
Private Const WM_MYMESSAGE As Integer = &H8000
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
' 获取接收方窗口句柄
Dim hWnd As IntPtr = FindWindow(Nothing, "接收方窗口标题")
If hWnd = IntPtr.Zero Then
MessageBox.Show("接收方窗口不存在!")
Return
End If
' 发送消息
Dim msg As String = "Hello World!"
Dim buffer As Byte() = Encoding.Unicode.GetBytes(msg)
SendMessage(hWnd, WM_MYMESSAGE, 0, buffer)
End Sub
' 接收方的代码
Private Const WM_MYMESSAGE As Integer = &H8000
Protected Overrides Sub WndProc(ByRef m As Message)
If m.Msg = WM_MYMESSAGE Then
' 解析消息
Dim buffer As Byte() = DirectCast(m.GetLParam(GetType(Byte())), Byte())
Dim msg As String = Encoding.Unicode.GetString(buffer)
' 处理消息
MessageBox.Show("接收到消息:" & msg)
Else
MyBase.WndProc(m)
End If
End Sub
```
在上面的示例中,发送方通过调用FindWindow函数获取接收方窗口的句柄,然后使用SendMessage函数向该窗口发送消息。接收方通过重载窗口过程并解析消息来处理接收到的消息。请注意,发送方和接收方需要使用相同的消息代码(在示例中为WM_MYMESSAGE)。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)