Just an addition to Yusuf's Answer:
You usually need to handle both
KeyDown
and
KeyUp
.
For example, you press Right and Up means you're moving diagonally north-east, if you will, but if you simply remove Right and keep Up presses, you change direction. Just an example.
Also, you will gain well in supportability if you stop using auto-generated handlers and use anonymous method (with C# 3 and 4 even in lambda form which is even better):
MyControl.KeyDown += (sender, eventArgs) = {
var key = eventArgs.KeyData.ToString().ToLower();
KeySet.Add(key);
Act(key, true, KeySet)
}
MyControl.KeyUp += (sender, eventArgs) = {
var key = eventArgs.KeyData.ToString().ToLower();
KeySet.Remove(key);
Act(key, false, KeySet)
}
Assuming you support set of keys. This way, you can Act based on both most most recent key (second argument can indicate up or down), and a current KeySet (third argument).
The anonymous syntax is better because you can keep event assignment and handlers where you want them, your real handlers (methods) profiles can be free (you don't have to carry
sender
is you're not using it, sometimes you don't need
eventArgs
). And lambda form is better because you don't need to type exact types of the arguments -- they are obtained by compiler via type inference.