Here is a simple console application I whipped up to demonstrate:
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace YourNamespaceHere
{
class Program
{
[DllImport("user32.dll")]
static extern uint keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
static void Main(string[] args)
{
keybd_event((byte)Keys.H, 0, 0, 0);
keybd_event((byte)Keys.H, 0, 0x7F, 0);
keybd_event((byte)Keys.E, 0, 0, 0);
keybd_event((byte)Keys.E, 0, 0x7F, 0);
keybd_event((byte)Keys.L, 0, 0, 0);
keybd_event((byte)Keys.L, 0, 0x7F, 0);
keybd_event((byte)Keys.L, 0, 0, 0);
keybd_event((byte)Keys.L, 0, 0x7F, 0);
keybd_event((byte)Keys.O, 0, 0, 0);
keybd_event((byte)Keys.O, 0, 0x7F, 0);
}
}
}
I did two things here: first, I used the
System.Windows.Forms.Keys enumeration; this is basically the .NET version of the virtual-key constants. You need to cast them to
byte first, and (if you're creating a console app, rather than a Windows forms app) add a reference in your project. To add a reference, right-click the project name in the Solution Explorer, say 'add reference', and on the .NET tab, there will be one for
System.Windows.Forms. You need to do this before the matching
using directive will work. If you're creating a forms app, the reference will already be there, and the
using directive will too for any forms-derived classes you create.
The second thing I did was to use the constant 0x7F. This is simply the value of the
KEYEVENTF_KEYUP constant. Remember that each 'key down' event needs to be matched with a corresponding 'key up' event, or the system will think a key is still being held down.
Anyways, if you create a new console application, and copy-paste my code above in, it should work fine (after you add the reference, of course). To run it, don't do it from the IDE. Rather, open up a command window (Start -> Run -> type 'cmd' and hit ENTER), navigate to the directory where your program executable is, and run it. You should get output similar to the following:
C:\PathToYourExecutable>NameOfYourExecutable
C:\PathToYourExecutable>hello
The red text is what you type at the prompt. Hit ENTER, and the prompt will re-appear with the word 'hello' typed in already (green text). This is because the program simulated the keystrokes, and they were still in the buffer.