Question

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);
            }
        }
    }
}
Was it helpful?

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.

OTHER TIPS

So I used code from this url: SendKeys.Send and Windows Key

And it works fine!

using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ConsoleApplication69
{
    class Program
    {
        static void Main(string[] args)
        {
            KeyboardSend.KeyDown(Keys.LWin);
            KeyboardSend.KeyUp(Keys.LWin);
        }
    }

    static class KeyboardSend
    {
        [DllImport("user32.dll")]
        private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

        private const int KEYEVENTF_EXTENDEDKEY = 1;
        private const int KEYEVENTF_KEYUP = 2;

        public static void KeyDown(Keys vKey)
        {
            keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY, 0);
        }

        public static void KeyUp(Keys vKey)
        {
            keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);


 }


}

}

tnx for help everybody!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top