C# WinApi - Key up not working

395 views Asked by At

I am trying to send keypresses to multiple windows at once. I have made a method to find the windows I need, and I have confirmed that it works. My problem is, that the keys I send get stuck.

Here I am sending the key 'W', this works. The problem is that the key never gets released. I have tried to fix this in multiple ways, but I can't seem to fix it for the life of me.

Edit: It seems that when I call SendMessage(Window, 0x0101, ((IntPtr)k), (IntPtr)0); it presses the key down instead of up, although the documentation clearly states that WM_KEYUP is 0x0101.

TL;DR how do I release a key with WinApi?

class Program
{
    static void Main(string[] args)
    {
        //This part works, method is uneccessary to know
        List<IntPtr> Windows = FindWindows("Minecraft 1.8.7").ToList();

        foreach (IntPtr win in Windows)
            SendKeyPress((ushort)Keys.W, win);
    }

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

    public static void SendKeyPress(ushort k, IntPtr Window)
    {
        //I tried with 0x0101 and 0x0100 aswell
        const uint WM_KEYDOWN = 0x100;
        const uint WM_KEYUP = 0x101;
        const uint WM_SYSCOMMAND = 0x018;
        const uint SC_CLOSE = 0x053;

        //I tried with PostMessage
        //I also tried putting a sleep statement between these two:
        SendMessage(Window, WM_KEYDOWN, ((IntPtr)k), (IntPtr)0);
        SendMessage(Window, WM_KEYUP, ((IntPtr)k), (IntPtr)0);
    }
}
0

There are 0 answers