How to call presskey (F9) in external application from C#?

  c++, console, keyboard-shortcuts, virtual-keyboard, windows

I’m trying programmatically press a key in other app.
Using functions of user32.dll (btw, does it make sense if the app is 64-bit application). I do smth like this:

const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
const uint KEYEVENTF_KEYUP = 0x0002;
private const int VK_F9 = 0x78;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindowEx(
        IntPtr hwndParent, IntPtr hwndChildAfter, string className, string windowName
        );
[DllImport("user32.dll")]
static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);


static void Main(string[] args)
    {

        IntPtr iHandle = FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, "program_name");
        SetForegroundWindow(iHandle);
        SetFocus(iHandle);         

        keybd_event(VK_F9, 0x45, KEYEVENTF_EXTENDEDKEY | 0, (UIntPtr)0);
        keybd_event(VK_F9, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0);
    }

But doesn’t work. I get the handle and focus seems to be working too. Just no press key.

Source: Windows Questions

LEAVE A COMMENT