C#PostMessage语法,尝试将WM_CHAR发布到另一个应用程序窗口

时间:2012-07-06 15:52:18

标签: c# winforms winapi formatting

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

    public const Int32 WM_CHAR = 0x0102;
    public const Int32 WM_KEYDOWN = 0x0100;
    public const Int32 WM_KEYUP = 0x0101;
    public const Int32 VK_RETURN = 0x0D;

    public Form1()
    {
        InitializeComponent();
    }

    public bool working;

    private void button1_Click(object sender, EventArgs e)
    {
        Process[] proc = Process.GetProcessesByName("processname");

        if (proc[0] == null || proc.Length == 0)
        {
            Debug.WriteLine("Process not found.");
            return;
        }

        foreach (char c in textBox1.Text)
        {
            // char ascii value in decimal
            int charValue = c;

            // char ascii value in hex
            string hexValue = charValue.ToString("X");

            IntPtr val = new IntPtr(c);

            Debug.WriteLine(c + " = dec: " + charValue + ", hex: " + hexValue + ", val: " + val);

            PostMessage(proc[0].MainWindowHandle, WM_KEYDOWN, val, new IntPtr(0));
            PostMessage(proc[0].MainWindowHandle, WM_CHAR, val, new IntPtr(0));
            PostMessage(proc[0].MainWindowHandle, WM_KEYUP, val, new IntPtr(0));

            PostMessage(proc[0].MainWindowHandle, WM_KEYDOWN, new IntPtr(VK_RETURN), new IntPtr(0));
            PostMessage(proc[0].MainWindowHandle, WM_KEYUP, new IntPtr(VK_RETURN), new IntPtr(0));
        }
    } 
}

如果我设置val = char 'm'(dec:109,十六进制:0x6D),那么当窗口获取消息时,由于某种原因(即dec 45,十六进制0x2D)显示字符' - '。我最初怀疑hex / dec格式问题,但我错了。 作为一个winapi新手,我的问题似乎是使用PostMessage()语法。如何发送正确的消息以使窗口显示正确的字符?

2 个答案:

答案 0 :(得分:4)

0x6C和108在C#中是相同的,都是整数,所以......

IntPtr val = new IntPtr(0x6C)

IntPtr val = new IntPtr(108)

在功能上是等同的。

因此,在上面的代码中,您应该可以使用:

IntPtr val = new IntPtr((Int32)c);

答案 1 :(得分:0)

我所有混淆的根源来自于PostMessage的{​​{1}}语法。我假设WM_CHAR是一个标准的ascii十六进制密码,但事实并非如此。它实际上是(十六进制)virtual keycode

这解释了为什么0x6D发送的是减号而不是'm'!