A WPF application has a Test()
method that is called when a keyboard shortcut is pressed CTRL+G.
The method call works because the string test
is printed to the console, from the first line of the method.
The method should programmatically press the key combination CTRL+A to select the text in any input field, but this does not happen.
I tried 3 ways:
First: The System.Windows.Forms.SendKeys.SendWait()
method, which takes a string, where ^
is CTRL - according to documentation
private void Test(object sender, EventArgs e)
{
Console.WriteLine("test");
SendKeys.SendWait("^A");
}
However, there is no pressing.
Second: Implementation via user32.dll
, solution taken from here:
[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
public static void PressKey(Keys key, bool up)
{
const int KEYEVENTF_EXTENDEDKEY = 0x1;
const int KEYEVENTF_KEYUP = 0x2;
if (up)
keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0);
else
keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0);
}
private void Test(object sender, EventArgs e)
{
Console.WriteLine("test");
PressKey(Keys.ControlKey, up: false);
PressKey(Keys.A, up: false);
PressKey(Keys.A, up: true);
PressKey(Keys.ControlKey, up: true);
}
But in this case, nothing happens.
Third: Installed the package: Install-Package InputSimulator
:
private static void Test(object sender, EventArgs e)
{
Console.WriteLine("test");
var simu = new InputSimulator();
simu.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_A);
}
Full code: https://pastebin.com/ay8vRtjA
There are no errors, what am I doing wrong?