Search code examples
c#.netwindowswinapipinvoke

Emulating of keyboard events not working C#


I'm trying to emulate some key events by using WinAPI. I want to press a WIN-key, but my code is not working. In example i use VK_F1 for every proc.

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

namespace ConsoleApplication69
{
    class Program
    {
        const UInt32 WM_KEYDOWN = 0x0100;
        const UInt32 WM_KEYUP = 0x0101;
        const int VK_F1 = 112;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

        static void Main(string[] args)
        {
            Process[] processes = Process.GetProcesses();

            foreach (Process proc in processes)
            {
                SendMessage(proc.MainWindowHandle, WM_KEYDOWN, new IntPtr(VK_F1), IntPtr.Zero);
                SendMessage(proc.MainWindowHandle, WM_KEYUP, new IntPtr(VK_F1), IntPtr.Zero);
            }
        }
    }
}

Solution

  • To simulate keyboard input, use SendInput. That's exactly what this API does. "Sending F1 to every window" is not a good idea, because you'll be sending keystrokes to windows that don't have keyboard focus. Who knows how they'll respond.

    There are a lot more nuances to keyboard input than you're accounting for; See this question for considerations about emulating keyboard input.