Reputation: 3
I have an application which want to detect multiple keys on Keyboard (keydown event in c#). In the last, i have limited keys detection (may be 4 keys) on event keydown and also i can't fire the event when "fn" keys keydown. there are 2 question here: 1. How to detect keys as many as possible 2. How to detect Fn keys when keyboard keydown event.
Here, I us globalKeyboardHook library that i found from others solution.
private void Form1_Load(object sender, EventArgs e)
{
gkh.HookedKeys.Add(Keys.A);
gkh.HookedKeys.Add(Keys.B);
gkh.HookedKeys.Add(Keys.D);
gkh.HookedKeys.Add(Keys.F);
gkh.HookedKeys.Add(Keys.G);
gkh.HookedKeys.Add(Keys.H);
gkh.HookedKeys.Add(Keys.J);
gkh.HookedKeys.Add(Keys.K);
gkh.HookedKeys.Add(Keys.L);
gkh.HookedKeys.Add(Keys.Z);
gkh.HookedKeys.Add(Keys.X);
gkh.HookedKeys.Add(Keys.C);
gkh.HookedKeys.Add(Keys.V);
gkh.HookedKeys.Add(Keys.B);
gkh.HookedKeys.Add(Keys.N);
gkh.HookedKeys.Add(Keys.M);
gkh.HookedKeys.Add(Keys.Q);
gkh.HookedKeys.Add(Keys.W);
gkh.HookedKeys.Add(Keys.E);
gkh.HookedKeys.Add(Keys.R);
gkh.HookedKeys.Add(Keys.T);
gkh.HookedKeys.Add(Keys.Y);
gkh.HookedKeys.Add(Keys.U);
gkh.HookedKeys.Add(Keys.I);
gkh.HookedKeys.Add(Keys.O);
gkh.HookedKeys.Add(Keys.P);
gkh.HookedKeys.Add(Keys.NumLock);
gkh.HookedKeys.Add(Keys.Insert);
gkh.HookedKeys.Add(Keys.FinalMode);
gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
}
void gkh_KeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine(e.KeyCode.ToString());
e.Handled = true;
}
I am really pleasure, if you can help me. thanks.
Upvotes: 0
Views: 1403
Reputation: 7921
There is a managed library MouseKeyHook as nuget which has support for detecting shortcuts, key combinations and sequences. Source code on github. Here is a usage example:
void DoSomething()
{
Console.WriteLine("You pressed UNDO");
}
Hook.AppEvents().OnCombination(new Dictionary<Combination, Action>
{
{Combination.FromString("Control+Z"), DoSomething},
{Combination.FromString("Shift+Alt+Enter"), () => { Console.WriteLine("You Pressed FULL SCREEN"); }}
});
For more information see: Detecting Key Combinations and Seuqnces
Upvotes: 0
Reputation: 63722
You can't get a KeyDown
event with multiple keys.
However, you can either check for keys that are currently pressed, or you can keep track of all those that are Down
at the moment (record them when you get KeyDown
and remove when you get KeyUp
).
There is a fixed limit to keys being pressed simultaneously based on the hardware keyboard. It may very well be that some key combinations only allow you to register two keys simultaneously, while others are more useable. And of course, there's gaming keyboards that can easily keep track of 20 or more at a time.
Upvotes: 1