0

Is there a way to be always the first application to receive input from devices(e.g. keyboard and mouse) even if it's not the foreground application? Is this possible to do with a standalone application without needing to tweak the registry?

jsanalytics
  • 13,058
  • 4
  • 22
  • 43
mohammad alam
  • 89
  • 1
  • 3
  • 9
  • 3
    With a keyboard hook: https://msdn.microsoft.com/en-us/library/windows/desktop/ms644959(v=vs.85).aspx – Dai Nov 18 '17 at 02:32
  • For the keyboard part, you're looking for a background key press listener. Here's an example using C#: https://stackoverflow.com/questions/5852455/background-key-press-listener – Ergwun Nov 18 '17 at 04:53
  • This library looks like it might help you too: https://github.com/gmamaladze/globalmousekeyhook – Ergwun Nov 18 '17 at 04:55

1 Answers1

0

There's a nuget package for that:

nuget install MouseKeyHook

From the project's readme

private IKeyboardMouseEvents m_GlobalHook;

public void Subscribe()
{
    // Note: for the application hook, use the Hook.AppEvents() instead
    m_GlobalHook = Hook.GlobalEvents();

    m_GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
    m_GlobalHook.KeyPress += GlobalHookKeyPress;
}

private void GlobalHookKeyPress(object sender, KeyPressEventArgs e)
{
    Console.WriteLine("KeyPress: \t{0}", e.KeyChar);
}

private void GlobalHookMouseDownExt(object sender, MouseEventExtArgs e)
{
    Console.WriteLine("MouseDown: \t{0}; \t System Timestamp: \t{1}", e.Button, e.Timestamp);

    // uncommenting the following line will suppress the middle mouse button click
    // if (e.Buttons == MouseButtons.Middle) { e.Handled = true; }
}

public void Unsubscribe()
{
    m_GlobalHook.MouseDownExt -= GlobalHookMouseDownExt;
    m_GlobalHook.KeyPress -= GlobalHookKeyPress;

    //It is recommened to dispose it
    m_GlobalHook.Dispose();
}
Ergwun
  • 12,579
  • 7
  • 56
  • 83