Search code examples
c#stringkeyoutputexecute

How to execute a string by key (F12)?


I am a bit a newbie on C#, what I am actually looking for is that the my C# Form is running on te background, and by pressing "F12" for example, the output is a string on screen.

I hope my question is clear enough.

Thanks in advance.


Solution

  • From your comments what you are looking for is a Global Key Hook,

    This would take a while to write up an answer and would be difficult for me to do as I don't know the make up of your application. However the majority of the code needed is here: http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx

    You will want to implement this into your application, the way I would use it is: Have a run button on the screen, when the user clicks that it will minimize the program to the taskbar, and then initiate KeyHooks.

    Tell the Keyhook to listen for F12 key.

    I would then once the key has been pressed use SendKeys.Send to send the text to the focused window: http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send(v=vs.110).aspx

    So you can use a textbox from your form to populate the sendkeys:

    SendKeys.Send(txtTextboxA.Text);
    

    Or you can make it send the same thing each time using the SendKeys characters

    SendKeys.Send("I am going to be sent");
    

    Keyhooks takes a while to get your head around but once set up it works like a charm, I would suggest having a go at this and then if you get stuck ask a new question :).

    EDIT - Added more KeyHook references

    There are also some codeprojects that may help you learn better:

    http://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook