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. However, it seems to always lose 0-2 characters at the beginning of the message. 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. 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:
[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. If so, depending on the version of Delphi it may or may not be a Unicode application. 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.
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.