[英]C# PostMessage - How to prevent data loss?
I have an application that will form a packet and send the packet data to an external program to send. 我有一个将形成数据包并将数据包数据发送到外部程序进行发送的应用程序。 I have everything working, but my only method I know that doesn't require the window to be the foremost is PostMessage. 我可以正常工作,但是我知道的唯一不需要窗口成为首要条件的方法就是PostMessage。 However, it seems to always lose 0-2 characters at the beginning of the message. 但是,它似乎总是在消息开头丢失0-2个字符。 Is there a way I can make a check to prevent the loss? 有什么方法可以检查以防止损失? I've tried looping GetLastError() and re-sending it if it's 0, but it doesn't help any. 我试过循环GetLastError(),如果它为0,则重新发送它,但是它没有任何帮助。 Here's the code I've gotten so far: 这是到目前为止我得到的代码:
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;
}
And here are the definitions in TextSend class: 这是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);
The fact that you're finding a TEdit and a TButton makes me think that the target application was written in Delphi. 您正在找到TEdit和TButton的事实使我认为目标应用程序是用Delphi编写的。 If so, depending on the version of Delphi it may or may not be a Unicode application. 如果是这样,则取决于Delphi的版本,它可能是也可能不是Unicode应用程序。 You're calling PostMessageA instead of PostMessageW which means it's sending a single-byte Ansi char instead of a 16-bit Unicode char from the c# application. 您正在调用PostMessageA而不是PostMessageW,这意味着它正在从c#应用程序发送单字节Ansi字符而不是16位Unicode字符。
Do you have source to the target application? 您有目标应用程序的源代码吗? Stuffing data in an edit box and clicking a button seems a bit fragile. 将数据填充到编辑框中并单击按钮似乎有些脆弱。 If you can modify the target application there are certainly other options available than to send one character at a time. 如果您可以修改目标应用程序,则肯定还有其他选择,而不是一次发送一个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.