سؤال

I have a function in WinForms C# app that sends a string (from a textbox) to an active CMD window, using a button.
Unfortunately, if the textbox contains multiple zeros (0000x000F22000), it returns just one zero: 0x0F220

How can I fix this?

private void but_run_Click(object sender, EventArgs e)
{

        uint wparam = 0 << 29 | 0;

        int i = 0;
        for (i = 0; i < textBox1.Text.Length; i++)
        {
            //PostMessage(child, WM_KEYDOWN, (IntPtr)Keys.Enter, (IntPtr)wparam);
            PostMessage(cmdHwnd, WM_CHAR, (int)textBox1.Text[i], 0);
        }
        PostMessage(cmdHwnd, WM_KEYDOWN, (IntPtr)Keys.Enter, (IntPtr)wparam);

}
هل كانت مفيدة؟

المحلول

You could try using the lParam to specify repeat key presses. Also, pay attention - PostMessage has lParam as the fourth parameter (wParam is before lParam), you're mixing it up in your code.

Next, don't use (int)someChar. You should use the Encoding classes to get byte values from chars.

Use SendMessage instead of PostMessage. PostMessage is asynchronous and can complicate a lot of stuff for you. You don't need the asynchronicity, so don't use it.

Next, why use WM_CHAR? I'd say WM_SETTEXT would be way more appropriate - you can send the whole text at once. Just be careful about using the native resources (eg. the string). To make this as easy as possible, you can make yourself an overload of the SendMessage method:

const uint WM_SETTEXT = 0x000C;

[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, unit Msg, 
   IntPtr wParam, string lParam);

You can then simply call:

SendMessage(cmdHwnd, WM_SETTEXT, IntPtr.Zero, textBox1.Text);

نصائح أخرى

I've managed to do it like this:

[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindow(IntPtr ZeroOnly, string lpWindowName);

[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

const int WM_CHAR = 0x0102;

public void sendText(string pText, string pCaption)
    {
        IntPtr wndHndl = FindWindow(IntPtr.Zero, pCaption);
        char[] tmpText = pText.ToCharArray();
        foreach (char c in tmpText)
        {
            System.Threading.Thread.Sleep(50);
            PostMessage(wndHndl, WM_CHAR, (IntPtr)c, IntPtr.Zero);
        }
    }

Where pText is the input string and pCaption is title of the window.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top