C#语法PostMessage的,试图发布WM_CHAR到另一个应用程序窗口(C# PostMess

2019-09-19 04:40发布

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' (它是分解:109,己烷:0x6D),然后当窗口得到它示出了炭消息“ - ”由于某种原因(这是十进制45,十六进制0x2D)。 我初步怀疑六角/ DEC格式化的问题,但我错了。 作为一个新手WINAPI,我的问题似乎与PostMessage的()语法。 我怎么能发送正确的消息有窗口中显示正确的字符?

Answer 1:

0x6C和108在C#中同样的事情,无论是整数,所以...

IntPtr val = new IntPtr(0x6C)

IntPtr val = new IntPtr(108)

在功能上equivilant。

因此,在上面的代码中,你应该能够使用:

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


Answer 2:

我的所有问题的根源来自朵朵PostMessage语法WM_CHAR 。 我假设wParam是一个标准的ASCII六角键码,事实并非如此。 它实际上是一个(十六进制) 的虚拟键代码 。

这就解释了为什么0x6D将派遣减,而不是“M”!



文章来源: C# PostMessage syntax, trying to post a WM_CHAR to another applications window