0

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.

Update. Below code didn't work either. I code console application:

using System.Windows.Forms;
static void Main(string[] args)
{

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

    SendKeys.SendWait("{F9}");
}

Update 2. Both ways actually worked. In didn't work in debug mode as focus obviously changes back to VS.

Nikky Leed
  • 1
  • 1
  • 2
  • I think this question is answered [here](https://stackoverflow.com/questions/19171081/how-can-i-capture-a-key-press-outside-of-the-form). – Carrivas Nov 25 '21 at 12:34
  • 1
    @Carrivas not really, that Q&A is about *capturing* key events if your application is not in focus, OP is asking about *sending* key events to another application, to which [this](https://stackoverflow.com/a/15292428/9363973) Q&A is the solution – MindSwipe Nov 25 '21 at 12:37
  • SendKeys.SendWait("{F9}"); didn't work either. I use console project. – Nikky Leed Nov 25 '21 at 13:03

0 Answers0