0

In Visual Studio, how can I get the keys pressed while the application is not open by C#?

I made a game trainer and I already got it working. Problem is that I have to continuously open the trainer if I want to use the cheats. So every time I open up the game, I minimize the trainer. But if the trainer is not selected, I cant press ctrl+e or ctrl+q to activate the shortcut.

How can I get the trainer to get pressed keys while not open?

I have something like this right now.

 private void Form1_KeyDown(object sender, KeyEventArgs e) 
        {
            if (Control.ModifierKeys == Keys.Control)
            {
                if (e.KeyCode == Keys.E) //When ctrl+e pressed, this runs
                {
}
Sascha
  • 1,210
  • 1
  • 17
  • 33

2 Answers2

0

You need to use a global keyboard hook, there are a lot of examples around but here is one on codeproject thats pretty simple to use.

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

Your going to have to use the SetWindowsHookEX in the user32.dll

[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId); 
0

If you want to react to some specific keyboard shortcuts, you can use the API Function RegisterHotKey. See https://stackoverflow.com/a/27309185/101087 for an example how to use it from C#.

Community
  • 1
  • 1
NineBerry
  • 26,306
  • 3
  • 62
  • 93