Reputation: 3855
I have a block of identical code for both the KeyUp
and KeyDown
events; the only difference is in one single line of code, which changes button.BackColor
to Color.Gray
or Color.White
accordingly. I want to put this block of code into a separate method to avoid repetition, and the single line that is different for the two events should look like:
button.BackColor = (KeyUp was fired) ? Color.Gray : Color.White;
The method accepts KeyEventArgs e
as a parameter, but I can't figure out how to determine whether e
is of type KeyUp
or KeyDown
. In C# (winforms), is there an analog to event.type
property in JavaScript? Otherwise, any other way to do this? Thanks
Upvotes: 0
Views: 191
Reputation: 19416
There is no way from the System.Windows.Forms.KeyEventArgs
to determine whether the event has been raised as the result of a KeyUp
or KeyDown
event. Your best bet would be to have different handling methods which both call a common method, i.e.
private void OnKeyDown(object sender, KeyEventArgs eventArgs)
{
HandleKeyState(false, eventArgs);
}
private void OnKeyUp(object sender, KeyEventArgs eventArgs)
{
HandleKeyState(true, eventArgs);
}
private void HandleKeyState(bool isKeyUp, KeyEventArgs eventArgs)
{
button.BackColor = isKeyUp ? Color.Gray : Color.White;
}
Upvotes: 2