-2

I have created a WinForms app, and put a button in it.

I want to code an event, that whenever I click the button it will automatically simulate an ALT + 2 key press on the keyboard.

How can I do this?

TaW
  • 53,122
  • 8
  • 69
  • 111
Shaxib
  • 43
  • 2
  • 7

1 Answers1

0

.Net have a class in System.Windows.Forms namespace that's called SendKeys.
It allows you to send keys to mimic keyboard hits.
You need a reference to System.Windows.Forms.dll (Note: this does not have to be a winforms application for that), and then you can simply use SendKeys.Send(%2) to mimic a user pressing alt+2.

A full list of supported special keys can be found in the msdn page I've linked to.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • Thanks ill try it soon :), also you know if it send those key in the same time? or just one after the other? – Shaxib Aug 14 '15 at 15:03
  • @Shaxib: every call to `Send` will send the keys you specify in the same time. so if you want to mimic the user typing *Shaxib*, you will have to use `SendKeys.Send` for each letter. – Zohar Peled Aug 14 '15 at 15:14
  • Glad to help :-) Yes, I am. you are from india, I guess? – Zohar Peled Aug 14 '15 at 15:18
  • Lol no, Israeli as well :P There's a long story behind my nickname – Shaxib Aug 14 '15 at 15:21
  • @Mystra007 sure indeed XD By the way Zohar, do you know how can i hook my program to a specific proccess such as "chrome.exe"? – Shaxib Aug 14 '15 at 15:32
  • something like Process[] processes = Process.GetProcessesByName("chrome"). You might need to P/invoke the Windows API to send keys to it. This thread would be a good start: http://stackoverflow.com/questions/15292175/c-sharp-using-sendkey-function-to-send-a-key-to-another-application. Note that there might be more than one chrome.exe as browser often runs several thread but that thread should give you some keywords to start your research :) Sends Zohan my regards lol – Mystra007 Aug 14 '15 at 15:50