简体   繁体   中英

Using PostMessage() or SendMessage() to send uppercase letters

I'm trying to send uppercase letters or symbols (,@# etc): using the PostMessage() function:

[DllImport("user32.dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

I tried sending both shift and the letter I want to send in upper case but it doesn't seem to work:

        public const uint WM_KEYUP = 0x0101;
        public const uint WM_KEYDOWN = 0x100;

        void function()
        {
            Keys key = Keys.A;
            Keys shift = Keys.ShiftKey;

            PostMessage(process.MainWindowHandle, WM_KEYDOWN, (IntPtr)shift, IntPtr.Zero);
            PostMessage(process.MainWindowHandle, WM_KEYDOWN, (IntPtr)key, IntPtr.Zero);
            PostMessage(process.MainWindowHandle, WM_KEYUP, (IntPtr)shift, IntPtr.Zero);
            PostMessage(process.MainWindowHandle, WM_KEYUP, (IntPtr)key, IntPtr.Zero);
        }

Edit: for those wondering: I ended up using SendInput() to send the shift key press, because apparently many games don't detect the shift key press the same way they detect other key presses that's why it didn't detect the shift key press when I tried sending it with PostMessage(), you can also use keybd_event() and SendKeys(). Note: that these methods don't send the keys to a specific process.

Try this instead of using WM_KEYDOWN and WM_KEYUP:

        public const uint WM_CHAR = 0x0102;

            ...

            PostMessage(process.MainWindowHandle, WM_CHAR, (IntPtr)'A', IntPtr.Zero);

Full Solution: Create a C# Console App (Mine was .NET Framework 4.7.2)

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace PostMessageTest
{
    class Program
    {
        [DllImport("user32.dll")]
        public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
        public const uint WM_CHAR = 0x0102;

        public static void function()
        {
            IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;
            Console.WriteLine("Sending Keys...");
            PostMessage(handle, WM_CHAR, (IntPtr)'A', IntPtr.Zero); // 0x41
        }

        static void Main(string[] args)
        {
            function();
            Console.Read();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM