0

I want a console application to run as long as i press a specified key, even outside of the programm. For example the programm is running in the background und when i am writing something e.g. in word and press a specific key, the console application does something.

I started with this:

static void Main(string[] args)
    { 
        ConsoleKeyInfo keyinfo;

        do
        {
            keyinfo = Console.ReadKey();
            //Do something
        }
        while (keyinfo.Key != ConsoleKey.F10);
    }    

But the problem here is, that it stops and waits for a key pressed until it keeps going. I want to run it in the background and always checking when i am pressing a specific key.

Any solutions?

Julian
  • 67
  • 9
  • Check: https://stackoverflow.com/questions/7196883/capture-media-keys-when-application-is-minimized/7730869#7730869 – SpiderCode Dec 06 '17 at 09:42

1 Answers1

-1

You can use the events provided by the static class HookManager.

You only need to add one of the events (included mouse activity):

UserActivityHook actHook;
void MainFormLoad(object sender, System.EventArgs e)
{
    actHook= new UserActivityHook(); // crate an instance

    // hang on events

    actHook.OnMouseActivity+=new MouseEventHandler(MouseMoved);
    actHook.KeyDown+=new KeyEventHandler(MyKeyDown);
    actHook.KeyPress+=new KeyPressEventHandler(MyKeyPress);
    actHook.KeyUp+=new KeyEventHandler(MyKeyUp);
}

Example for KeyDown event:

public void MouseMoved(object sender, KeyEventArgs e)
        {
            Keys key = e.KeyCode;
            Console.WriteLine(key.ToString());
        }

ReadKey method runs only when you type something inside the console.

More details: https://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C