0

好的,这个问题困扰我很久了。

我有通过 PostMessage 将字符串传递给客户端的服务代码:

 Public Sub SendToClient(msgs As String, types As Integer, hwnd As Long)

        postMessage(hwnd, 0, Nothing, msgs)

    End Sub

然后我有接收字符串的客户端:

 Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If (m.Msg = 0) Then
            Dim a as string
            a = Marshal.PtrToStringAuto(m.LParam)
           end if
        MyBase.WndProc(m)
    End Sub

但是,客户端有时会发送一个错误,或者一些混乱的二进制数据,甚至只是一个空白字符串。顺便说一句,m.LParam 是一个数字。

有人可以告诉我通过 postmessage 发送/接收字符串的正确方法是什么。

4

1 回答 1

1

我这样做:

Public Sub SendMessageToApp(ByVal NombreVentana As String, ByVal Mensaje As String, ByVal sender As Form)
        Dim hWnd As IntPtr
        Dim mCopyData As COPYDATASTRUCT

        hWnd = CType(FindWindow(Nothing, NombreVentana), IntPtr)
        Dim message As New System.Text.StringBuilder

        If (CInt(hWnd) <> 0) Then

            message.Append(Mensaje)

            Dim pCopyData As IntPtr = Marshal.AllocHGlobal(message.Length() + 40)


            mCopyData.lpData = Marshal.StringToHGlobalAnsi(message.ToString)
            mCopyData.cbData = message.Length
            mCopyData.dwData = CType(_messageID, IntPtr)
            Marshal.StructureToPtr(mCopyData, pCopyData, False)

            SendMessage(hWnd, WM_COPYDATA, CInt(sender.Handle), pCopyData)
            Marshal.FreeHGlobal(mCopyData.lpData)
            Marshal.FreeHGlobal(pCopyData)

        End If
    End Sub

接收窗口:

Declarations and definitions:

 Const WM_COPYDATA As Integer = 74
    Const SIG_LENGTH As Integer = 36
    Const MAX_COPY_LENGTH As Integer = 128
    Const SigConnect As String = "F7B82657-BD18-4ee6-B182-78721293821C"
    Dim CDCount As Integer

    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Integer

    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
    (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, _
    ByVal lParam As IntPtr) As Integer

    Dim hWndSender As Integer
    Private Const _messageID As Integer = 10

    'Estructura obligatoria para poder utilizar el API CopyData
    <StructLayout(LayoutKind.Sequential)> _
    Private Structure COPYDATASTRUCT
        Public dwData As IntPtr
        Public cbData As Integer
        Public lpData As IntPtr
    End Structure

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)

        If m.Msg = WM_COPYDATA Then
            Dim Estructura As COPYDATASTRUCT
            Dim tipo As Type = Estructura.GetType
            Dim message As String

            Estructura = CType(m.GetLParam(GetType(COPYDATASTRUCT)), COPYDATASTRUCT)

            'Here you get the message
            message = Marshal.PtrToStringAnsi(Estructura.lpData, Estructura.cbData)

        End If
于 2013-06-07T07:00:25.710 回答