0

How can I detect if a key was pressed in a game (league of legends) using C#?

I used to do that with AHK with ease but I want to move to c# since I m studying it these days.

Do you guys have any suggestions?

wserr
  • 436
  • 1
  • 3
  • 12

3 Answers3

2

My friend implemented a thread level mouse/keyboard hook.

enter image description here

Just install the Nuget package and give me some feedback.

Install-Package -IncludePrerelease Winook

Example:

var processes = Process.GetProcessesByName("LeagueOfLegendProcessName");
_process = processes.FirstOrDefault();
if (_process == null)
{
    return;
}

_keyboardHook = new KeyboardHook(_process.Id);
_keyboardHook.MessageReceived += KeyboardHook_MessageReceived;

...

private void KeyboardHook_MessageReceived(object sender, KeyboardMessageEventArgs e)
{
    Debug.WriteLine($"Keyboard Virtual Key Code: {e.VirtualKeyCode}; Flags: {e.Flags:x}");
}
C1rdec
  • 1,647
  • 1
  • 21
  • 46
0

take a look at SetWindowsHookExA it will let you hook to mouse and kb events and look into pinvoke.net to learn how to do it.

Patrick Beynio
  • 788
  • 1
  • 6
  • 13
0

I would suggest you should always search in the documentations and read them carefully.

Bellow is an example of how to do it based on Microsoft documentation

// Uses the Keyboard.IsKeyDown to determine if a key is down.
// e is an instance of KeyEventArgs.
if (Keyboard.IsKeyDown(Key.Return))
{
    btnIsDown.Background = Brushes.Red;
}
else
{
    btnIsDown.Background = Brushes.AliceBlue;
}

Don't forget to import 'System.Windows.Input' namespace.

Follow the link 1 and Link 2 for more info.

Edit: This question is answered in this link: Trying to detect keypress

Mustafa Mohammadi
  • 1,433
  • 1
  • 12
  • 25
  • 1
    oh thanks for the answer but that will work only if I m on the form , but what if I were in a game ? –  May 13 '20 at 04:51
  • The code snippet I posted wouldn't matter where are you using it. It is not for form. Anywhere you can run this code, it should work. – Mustafa Mohammadi May 13 '20 at 04:53