C#PostMessage - 如何防止数据丢失?

时间:2012-01-02 02:07:49

标签: c# winapi sendmessage postmessage

我有一个应用程序,它将形成一个数据包并将数据包数据发送到外部程序进行发送。我有一切工作,但我知道的唯一方法不需要窗口是最重要的是PostMessage。但是,它似乎总是在消息开头丢失0-2个字符。有没有办法可以检查以防止丢失?我已经尝试循环GetLastError()并重新发送它,如果它是0,但它没有任何帮助。这是我到目前为止获得的代码:

    public void SendPacket(string packet)
    {
        //Get window name
        IntPtr hWnd = Window.FindWindow(null, "???????????");
        //Get the first edit box handle
        IntPtr edithWnd = Window.FindWindowEx(hWnd, IntPtr.Zero, "TEdit", "");
        //Get the handle for the send button
        IntPtr buttonhWnd = Window.FindWindowEx(hWnd, IntPtr.Zero, "TButton", "SEND");
        //Iterate twice to get the edit box I need
        edithWnd = Window.FindWindowEx(hWnd, edithWnd, "TEdit", "");
        edithWnd = Window.FindWindowEx(hWnd, edithWnd, "TEdit", "");
        foreach (Char c in packet)
        {
            SendCheck(c, edithWnd);
        }
        //Press button
        TextSend.PostMessageA(buttonhWnd, 0x00F5, 0, 0);
        //Clear the edit box
        TextSend.SendMessage(edithWnd, 0x000C, IntPtr.Zero, "");
    }

    public void SendCheck(char c, IntPtr handle)
    {
        //Send the character
        TextSend.PostMessageA(handle, 0x102, c, 1);
        //If error code is 0 (failure), resend that character
        if (TextSend.GetLastError() == 0)
            SendCheck(c, handle);
        return;
    }

以下是TextSend类中的定义:

        [DllImport("Kernel32.dll")]
        public static extern int GetLastError();
        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string s);  

1 个答案:

答案 0 :(得分:1)

你找到一个TEdit和一个TButton的事实让我觉得目标应用程序是用Delphi编写的。如果是这样,根据Delphi的版本,它可能是也可能不是Unicode应用程序。你正在调用PostMessageA而不是PostMessageW,这意味着它正在从c#应用程序发送单字节Ansi字符而不是16位Unicode字符。

您是否拥有目标应用程序的来源?在编辑框中填充数据并单击按钮似乎有点脆弱。如果您可以修改目标应用程序,那么肯定还有其他选项,而不是一次发送一个字符。

相关问题