如何向CMD发送一个有多个零的字符串?

时间:2014-01-23 07:50:17

标签: c# sendmessage

我在WinForms C#app中有一个函数,它使用一个按钮将一个字符串(从文本框)发送到一个活动的CMD窗口。
不幸的是,如果文本框包含多个零(0000x000F22000),则只返回一个零: 0x0F220

我该如何解决这个问题?

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);

}

2 个答案:

答案 0 :(得分:0)

您可以尝试使用lParam指定重复按键。此外,请注意 - PostMessagelParam作为第四个参数(wParamlParam之前),您将在代码中混合使用。

接下来,请勿使用(int)someChar。您应该使用Encoding类从字符中获取字节值。

使用SendMessage而不是PostMessage。 PostMessage是异步的,可能会让很多东西复杂化。你不需要异步性,所以不要使用它。

接下来,为什么要使用WM_CHAR?我会说WM_SETTEXT会更合适 - 你可以立即发送整个文本。请注意使用本机资源(例如字符串)。为了使这个变得尽可能简单,你可以让自己成为SendMessage方法的重载:

const uint WM_SETTEXT = 0x000C;

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

然后您可以简单地致电:

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

答案 1 :(得分:0)

我设法这样做了:

[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);
        }
    }

其中 pText 是输入字符串, pCaption 是窗口的标题。