January 21, 2005

Emulating keystrokes in Windows

One of the core functions in Shoot, a voice command program I wrote a couple of years ago, is the ability to emulate key presses programmatically.

There is a fairly straightforward way to do this in Windows 2000/XP, via the SendInput Win32 function. In Windows 98/ME things are somewhat more complicated: SendInput inserts the keystrokes in the Windows event queue, but DirectInput bypasses it and hooks directly into the keyboard driver.

As a result, any keystroke sent via SendInput is completely ignored by DirectInput applications. Pretty much every modern Windows-based game uses DirectInput, the main target for Shoot. The solution is to implement a Virtual Device Driver (VxD) that inserts the keystrokes directly into the keyboard driver buffer, and that is what I ended up doing for Shoot.

Here's how to use the SendInput function from C#. I stripped all the Win98/ME-related code. Not only would it make the code below significantly more complex, but it's probably useless by now. Who's using Win 98, anyway? Not even Microsoft supports it anymore :)

[StructLayout(LayoutKind.Sequential)]
private struct KEYBOARD_INPUT {
public uint type;
public ushort vk;
public ushort scanCode;
public uint flags;
public uint time;
public uint extrainfo;
public uint padding1;
public uint padding2;
}

[DllImport("User32.dll")]
private static extern uint SendInput(uint numberOfInputs, [MarshalAs(UnmanagedType.LPArray, SizeConst=1)] KEYBOARD_INPUT[] input, int structSize);

void press(int scanCode)
{
  sendKey(scanCode, true);
}

void release(int scanCode)
{
  sendKey(scanCode, false);
}

private void sendKey(int scanCode, bool press)
{
   KEYBOARD_INPUT[] input = new KEYBOARD_INPUT[1];
   input[0] = new KEYBOARD_INPUT();
   input[0].type = INPUT_KEYBOARD;
   input[0].flags = KEY_SCANCODE;

   if ((scanCode & 0xFF00) == 0xE000) { // extended key?
     input[0].flags |= KEY_EXTENDED;
   }

   if (press) { // press?
     input[0].scanCode = (ushort) (scanCode & 0xFF);
   }
   else { // release?
     input[0].scanCode = scanCode;
     input[0].flags |= KEY_UP;
   }

   uint result = SendInput(1, input, Marshal.SizeOf(input[0]));

   if (result != 1) {
     throw new Exception("Could not send key: " + scanCode);
   }
}

21 Comments:

Anonymous Anonymous said...

Ive worked a lot with this method, trying to use the SendInput and another one for a program a I am working on, with little success at all. I have another method which works on all but DirectX.

I cannot get this one to work anywhere though. Can you send a compilable version of this. and explain more about how you worked with the driver for a solution, as I saw that mentioned elsewhere as well.

James falazar@yahoo.com

May 10, 2005 1:29 PM  
Anonymous Anonymous said...

is that possible to put your vxd source inline ?

September 20, 2005 2:35 AM  
Anonymous Anonymous said...

Hi, Could you please send me the values for INPUT_KEYBOARD, KEY_EXTENDED, KEY_UP?

Thanks,

Emil.Aguinaldo@AP.EmersonProcess.Com

October 07, 2005 6:26 AM  
Blogger Daniel said...

This comment has been removed by a blog administrator.

June 03, 2006 5:44 AM  
Blogger Daniel said...

const uint INPUT_KEYBOARD = 1;
const int KEY_EXTENDED = 0x0001;
const uint KEY_UP = 0x0002;
const uint KEY_SCANCODE = 0x0004;

should do the job. see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputstructures/keybdinput.asp for more info

June 03, 2006 9:25 AM  
Blogger tom2 said...

It's
const uint KEY_SCANCODE = 0x0008;
and NOT 0x0004!!!!!!

Oh darn, I only wasted something like 5 hours because of this...

April 14, 2008 1:25 PM  
Blogger dghnfgj said...

This momentousdecree wow gold came as a great beacon gold in wow light of hope buy wow gold to millions of negroslaves wow gold kaufen who had been seared in the flames of withering injustice.maplestory mesos it came as a joyous daybreak to end the long night ofcaptivity.but one hundred years later,maplestory money we must face the tragic fact thatthe negro is still not free.maple money one hundred years later,sell wow gold the lifeof the negro is still sadly crippled by the manacles ofsegregation and the chains of discrimination. one hundred yearslater,maple story money the negro lives on a lonely island of poverty in themidst of a vast ocean of material prosperity.wow powerleveling one hundred yearslater,maple story power leveling the negro is still languishing in the corners of americansociety and finds himself an exile in his own land. so we havecome here today to dramatize wow powerleveln an appalling condition.in a ms mesos sense we have come to our nation''s capital to cash a check.when the architects of our republic wow powerleveln wrote the magnificent wordsof the constitution and the declaration of independence, theywere signing a promissory note maplestory power leveling to which every american was tofall heir. this note was a promise that all men would beguarranteed the inalienable rights of life, liberty, and thepursuit of happiness.it is obvious today that america has defaulted on thispromissory note insofar as her citizens of color are concerned.instead of honoring this sacred obligation, america has giventhe negro people a bad check which has come back markedinsufficient funds.justice is bankrupt. we refuse to believe that there areinsufficient funds in the great vaults of opportunity of thisnation. so we have come to cash this check -- a check that willgive us upon demand the riches of freedom and the security ofjustice. we have also come to this hallowed spot to remindamerica of the fierce urgency of now

February 06, 2009 11:41 PM  
Blogger nasha said...

Why was there no follow on bankruptcy then? The bailout of AIG FP went to (wow power leveling) hedge funds that bound credit swaps on Lehman failing or others betting on rating (wow power leveling) declines. AIG has drained over 100 billion from the government. Which had to go to (wow power leveling) those who bet on failures and downgrades. Many of whom (power leveling)were hedge funds. I-banks that had offsetting swaps needed the money from the AIG bailout or they would have been caught. Its an (wow powerleveling) insiders game and it takes just a little bit too much time for most people to think (wow gold) through where the AIG 100 billion bailout money went to, hedge funds and players, many of whom hire from the top ranks of DOJ, Fed, Treasury, etc. ZHANG XIAO CHEN

April 19, 2009 10:02 PM  
Blogger Kayla said...

www.crazypurchase.com Web site for the majority of the china wholesalers, and buy products wholesale to provide information and buy wholesale from china information exchange platform dedicated to becoming China Wholesale.

September 24, 2009 9:21 PM  
Blogger Kayla said...

Cell phones from simple communication became a full-featured entertainment terminal . Can be said that cell phone china new milestone in the industry. This fully demonstrates that, cheap cell phones entertainment has become the most sought after consumer applications and has become the focus of the mobil phones market.

September 24, 2009 9:21 PM  
Blogger Kayla said...

Present-day society, the rapid development of science and technology makes cell phones wholesale is no longer a simple phone communications equipment only. Wholesale cell phones have many features, entertainment, scalability, and so have a good expression of the discount cell phones will be to maximize the effectiveness of multimedia technology.

September 24, 2009 9:22 PM  
Blogger suspectx86 said...

I worked out the code like this, but everytime I send a key with the Press and Release Method...

I get an exception error:
Could not send key: 65

static void SendKey_A()
{
press(65);
release(65);
}

[StructLayout(LayoutKind.Sequential)]
private struct KEYBOARD_INPUT
{
public uint type;
public ushort vk;
public int scanCode;
public uint flags;
public uint time;
public uint extrainfo;
public uint padding1;
public uint padding2;
}

[DllImport("User32.dll")]
private static extern uint SendInput(uint numberOfInputs, [MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] KEYBOARD_INPUT[] input, int structSize);

static void press(int scanCode)
{
sendKey(scanCode, true);
}

static void release(int scanCode)
{
sendKey(scanCode, false);
}

public static void sendKey(int scanCode, bool press)
{
const uint INPUT_KEYBOARD = 1;
const int KEY_EXTENDED = 0x0001;
const uint KEY_UP = 0x0002;
const uint KEY_SCANCODE = 0x0008;
KEYBOARD_INPUT[] input = new KEYBOARD_INPUT[1];
input[0] = new KEYBOARD_INPUT();
input[0].type = INPUT_KEYBOARD;
input[0].flags = KEY_SCANCODE;

if ((scanCode & 0xFF00) == 0xE000)
{ // extended key?
input[0].flags |= KEY_EXTENDED;
}

if (press)
{ // press?
input[0].scanCode = (ushort)(scanCode & 0xFF);
}
else
{ // release?
input[0].scanCode = scanCode;
input[0].flags |= KEY_UP;
}

uint result = SendInput(1, input, Marshal.SizeOf(input[0]));

if (result != 1)
{
throw new Exception("Could not send key: " + scanCode);
}
}
}
}

October 18, 2009 10:42 PM  
Blogger Adi said...

Oes Tsetnoc | Mengembalikan Jati Diri Bangsa | Kenali dan Kunjungi Objek Wisata di Pandeglang | Oes tsetnoc | Online Marketing | Electronics Gadgets | etips solution | Travel Guide

October 27, 2009 12:40 AM  
Blogger crazyloko said...

buy products wholesaleThis phenomenom is typified by China Wholesalersthe rise ofbusiness. Incredible range of products available with China Wholesale “Low Price and High Quality” not only reaches directly to their target clients worldwide but also ensures that wholesale from china from China means margins you cannot find elsewhere and China Wholesale will skyroket your profits.china wholesale productsbuy china wholesalewholesale chinawholesale productsbuy products

October 27, 2009 12:46 AM  
Blogger The Jack said...

Thanks ever so much, very useful article. If you do not mind, please visit my article related to pandeglang district in Banten, Indonesia at Kenali dan Kunjungi Objek Wisata di Pandeglang or Kenali dan Kunjungi Objek Wisata di Pandeglang second and also Kenali dan Kunjungi Objek Wisata di Pandeglang Objek Wisata Air Terjun Curug Gendang or related to a leadership at Mengembalikan Jati Diri Bangsa and Oes Tsetnoc or Oes Tsetnoc the second and our hard work at Kerja Keras Adalah Energi Kita that's right Kerja Keras Adalah Energi Kita, and Kenali dan Kunjungi Objek Wisata di Pandeglang Memasuki Babak Akhir also Objek Wisata Taman Wisata Alam Carita, Kenali dan Kunjungi Objek Wisata di Pandeglang, or Kenali dan Kunjungi Objek Wisata di Pandeglang, also Kenali dan Kunjungi Objek Wisata di Pandeglang, or Kenali dan Kunjungi Objek Wisata di Pandeglang, also Kenali dan Kunjungi Objek Wisata di Pandeglang, or Kenali dan Kunjungi Objek Wisata di Pandeglang, also Kenali dan Kunjungi Objek Wisata di Pandeglang, or Kenali dan Kunjungi Objek Wisata di Pandeglang, very smart thank you!

October 28, 2009 11:03 PM  
Blogger Daniela said...

Find your great Travel News and sing the songs at Free Song Lyric or you can watch the drama at Korea Drama Online one of great korea drama is A Love to Kill if you go to travel to Indonesia learn Learn Indonesia Language first! And find your home cari rumah or make a blog Belajar membuat Blog find your home again rumah dijual and again at jual rumah then if you want buy a new laptop see the Laptop Price List or you can buy a New Blackberry and then take care your Health & Jewerly.

November 14, 2009 7:52 PM  
Blogger James Taylor said...

Life experience degrees | life experience master degree | online associate degree

December 03, 2009 10:22 PM  
Blogger James Taylor said...

life experience bachelor degree | online doctorate degree

December 03, 2009 10:23 PM  
Blogger nike said...

Nice work and thanks!
Running
Adidas currently manufactures several running shoesNike shoes, including the adiStar Control 5, the adiStar Ride
Cheap nike shoes
Discount nike shoes
the Supernova Sequence and the Supernova Cushion 7, among others.
Nike shox r4
nike shox shoes
Adidas also uses kangaroo leather to make their more expensive shoes.
Association football
One of the main focuses of Adidas is football kit and associated equipment.
puma cat
cheap sport shoes
Adidas also provides apparel and equipment for all teams in Major League Soccer. Adidas remain a major company in the supply of team kits for international football teams.
cheap nike shox
cheap nike max
Adidas also makes referee kits that are used in international competition and by many countries and leagues in the world. In the United States, referees wear the Adidas kits in MLS matches even though the primary referee supplier is Official Sports.
nike tn dollar
nike running shoes
The company has been an innovator in the area of footwear for the sport with notable examples including development of the Copa Mondial moulded boot on firm dry pitches for forty years.
nike air max tn
puma shoes
Adidas became renowned for advancing the "Predator" boot design.This design featured a ribbed rubber structure for the upper leather of the shoe, used to accent the movement of the ball.
discount puma shoes
puma mens shoes
The Predator also features the Craig Johnston invented "Traxion" sole. As the development and popularity of Football continued Adidas played a leading role in shaping the style of the play itself.
puma running shoes
puma shoes
FIFA, the sports governing body, commissioned specially designed footballs for use in its own World Cup tournaments to favour more attacking play.
ghd hair straighteners mk4
hair straightners
ghd iv styler hair straightener
ghd hair straightners
cheap ghd hair straighteners

December 09, 2009 4:58 PM  
Blogger nike said...

Clothing has always been a thing that has been given a great importance by human beings. It displays the attitude that the people exhibit.
ed hardy clothes
ed hardy shirts
Lots of brands have been existent in the clothing industry and a famous one among them is the Ed hardy clothing brand.
ed hardy jackets
ed hardy hoodies
The brand got its name from the famous American tattoo artist Ed Hardy. He was a very famous tattoo artist and has published many books on tattooing techniques.
ed hardy boots
ed hardy polo shirts
But his tattooing turned into a brand by the efforts of a company called Christian Audiger. This company was a very famous and very powerful company in the field of clothing.
ed hardy shoes
ed hardy jeans
They felt that it would be appropriate to create a brand called Ed hardy and use Hardy's art as the main selling point for the brand. This venture had turned out to be a very successful one and Ed hardy clothing is one of the most famous brands in the clothing industry.
ed hardy outerwear
ed hardy long sleeve shirts
The brand became very famous because it was worn by many famous celebrities like Madonna, Britney spears and also Sylvester Stallone.
ed hardy bags
ed hardy winter boots
The brand has clothes for men, women, and kids. They have also diversified their business by having a lot of accessories to support their clothing business.
ed hardy love kills slowly shirts
ed hardy love kills slowly shoes
ed hardy love kills slowly boots
for men they have a variety of products such as active wear, denim, outwear, swim trucks, sweaters, t-shirts, tops etc.
ed hardy trousers
ed hardy mens
the accessories include things such as belts, caps, scarves, shoes, socks, jeweler, sunglasses, ties and even wallets.
The art works is a unique combination of American and Japanese cultures. The unique selling proposition of the brand is the way in which the company has used the art works of Ed hardy.
ed hardy womens
ed hardy t shirts
ed hardy sunglasses

December 09, 2009 4:59 PM  
Blogger uwanna said...

gucci replica handbags
men gucci shoes
Gucci men sneakers
Gucci men moccasins
gucci women sneakers
gucci women boots
Gucci men boots
Gucci
Gucci shop
Gucci bags
Gucci shoes
Replica GUCCI SHOES
wholesale gucci shoes
cheap Gucci handbags
Gucci ON sale
Gucci Belts
Gucci small accessories
Gucci hats & scarves
Gucci wallets
Gucci Handbags
Women Gucci shoes
Men Gucci shoes
discount gucci shoes
cheap Gucci shoes

February 04, 2010 9:34 PM  

Post a Comment

Links to this post:

Create a Link

<< Home