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.