C# PostMessage syntax, trying to post a WM_CHAR to

2020-07-27 04:35发布

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

If I set val = char 'm' (which is dec: 109, hex: 0x6D) then when the window gets the message it shows the char '-' for some reason (which is dec 45, hex 0x2D). I initially suspected hex/dec formating issues but I was mistaken. As a winapi newbie, my problem seems to be with PostMessage() syntax. How can I send the correct message to have the window display the correct character?

2条回答
你好瞎i
2楼-- · 2020-07-27 05:04

The source of all my confusion stemmed from the PostMessage syntax for WM_CHAR. I assumed the wParam was a standard ascii hex keycode and it was not. It was actually a (hex) virtual keycode.

This explains why 0x6D was sending minus instead of 'm'!

查看更多
Deceive 欺骗
3楼-- · 2020-07-27 05:20

0x6C and 108 are the same thing in C#, both are integers, so...

IntPtr val = new IntPtr(0x6C)

and

IntPtr val = new IntPtr(108)

are functionally equivilant.

Therefore in your code above, you should be able to use:

IntPtr val = new IntPtr((Int32)c);
查看更多
登录 后发表回答