【发布时间】:2013-03-30 09:28:54
【问题描述】:
我正在尝试将结构化数据从我正在开发的 VB 2010 应用程序发送到期望字符串转换为字节数组的现有库。我在将数据作为字节数组发送时遇到问题 - 我可以将应该转换为字节的纯字符串发送到我编写的测试程序。
这是两个应用程序。首先是监听进程:
Imports System.Runtime.InteropServices
Public Class frmTest
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = frmTest.WM_COPYDATA Then
Dim data As CopyData
Dim message As String
' get the data...
data = CType(m.GetLParam(GetType(CopyData)), CopyData)
message = data.lpData
' add the message
txtTest.Text = message
' let them know we processed the message...
m.Result = New IntPtr(1)
Else
MyBase.WndProc(m)
End If
End Sub
Private Function UnicodeBytesToString(ByVal bytes() As Byte) As String
Return System.Text.Encoding.Unicode.GetString(bytes)
End Function
Private Const WM_COPYDATA As Integer = &H4A
<StructLayout(LayoutKind.Sequential)> _
Private Structure CopyData
Public dwData As IntPtr
Public cbData As Integer
Public lpData As String
End Structure
End Class
其次是发送数据的进程:
Imports System.Runtime.InteropServices
Imports System.Collections.Generic
Public Class frmMain
<StructLayout(LayoutKind.Sequential)> _
Private Structure CopyData
Public dwData As IntPtr
Public cbData As Integer
Public lpData As String
End Structure
Private Declare Auto Function SendMessage Lib "user32" _
(ByVal hWnd As IntPtr, _
ByVal Msg As Integer, _
ByVal wParam As IntPtr, _
ByRef lParam As CopyData) As Boolean
Private Declare Auto Function FindWindow Lib "user32" _
(ByVal lpClassName As String, _
ByVal lpWindowName As String) As IntPtr
Private Const WM_COPYDATA As Integer = &H4A
Private Sub cmdSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSend.Click
Dim ClientWindow As IntPtr
Dim a() As System.Diagnostics.Process = System.Diagnostics.Process.GetProcesses
For Each p In a
Console.WriteLine(p.ProcessName)
If p.ProcessName = "Listener" Then
ClientWindow = p.MainWindowHandle
Exit For
End If
Next
' make sure we found an active client window
If Not ClientWindow.Equals(IntPtr.Zero) Then
' if there is text to send
If txtText.Text.Length > 0 Then
Dim message As String = txtText.Text
Dim data As CopyData
' set up the data...
data.lpData = message
data.cbData = message.Length * Marshal.SystemDefaultCharSize
' send the data
frmMain.SendMessage(ClientWindow, frmMain.WM_COPYDATA, Me.Handle, data)
End If
Else
MsgBox("Could Not Find Active Client Window.")
End If
End Sub
Private Function UnicodeStringToBytes(
ByVal str As String) As Byte()
Return System.Text.Encoding.Unicode.GetBytes(str)
End Function
End Class
这一切都有效,但如果我将两者中的“Public lpData As String”更改为“Public lpData As Byte()”,然后将“data.lpData = message”修改为“data.lpData = UnicodeStringToBytes(message)” sender 进程和 'message = data.lpData' 到 'message = UnicodeBytesToString(data.lpData)' 在侦听器进程中崩溃。
如何将编码为字节数组的字符串从发送者发送到侦听器,以便侦听器将其解码回字符串?
我意识到将字符串作为字符串发送会更容易,但现有库需要它作为字节数组,所以我试图让我的发送者在这个测试监听器上工作,在那里我可以看到正在发生的事情。
提前致谢!
【问题讨论】:
-
感谢您的回复 - 我对 VB 不太熟悉,我已在接收应用程序中进行了更改,但我不确定您在发送应用程序中的意思。
标签: vb.net visual-studio bytearray sendmessage