user11130509
user11130509

Reputation:

how to detect key pressed in game with C#

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?

Upvotes: 0

Views: 542

Answers (3)

C1rdec
C1rdec

Reputation: 1687

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}");
}

Upvotes: 2

Mustafa Mohammadi
Mustafa Mohammadi

Reputation: 1463

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

Upvotes: 0

Patrick Beynio
Patrick Beynio

Reputation: 868

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.

Upvotes: 0

Related Questions