how to fire a keydown or keypress event

396 Views Asked by At

I want key press event fire without pressing a key by user. so I use

InputSimulator.SimulateKeyPress(VirtualKeyCode.VK_U);

also

System.Windows.Forms.SendKeys.Send("a");

that did not cause it so I use

    var key = Key.Insert;                    // Key to send
    var target = Keyboard.FocusedElement;    // Target element
    var routedEvent = Keyboard.KeyDownEvent; // Event to send

    target.RaiseEvent(
      new KeyEventArgs(
        Keyboard.PrimaryDevice,
        PresentationSource.FromVisual(target),
        0,
        key) { RoutedEvent = routedEvent }
    );

that make following error The name 'Key' does not exist in the current context I use

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Windows.Input;
using WindowsInput; 

and I write this codes on Form1_Load

1

There are 1 best solutions below

0
On BEST ANSWER

@Idle_Mind thanks. it works.

Posting comment as answer:

and I write this codes on Form1_Load

The Load() event occurs before the form has been displayed, therefore your keystroke(s) is being sent to whatever application had focus right before your program was run (probably Visual Studio if you're running from the IDE)

Move your test code to the Shown() event and you might get better results...