I'm writing an application which has multiple states. The states are swapped by pressing space, and current state is stored in an enum. I handle the swapping by KeyUp and KeyDown Event.
I want to achieve: When I press (and hold) the space key, I just wanna swap to the next phase, and wait until the space key is released. When it is released, the window does something (counting time using StopWatch and DispatcherTimer) and that stops after I press the space again, which also swaps to next state and so on.
The window holds properties of the current phasis (Phase) and event methods for the KeyUp and KeyDown events (called KeyRelease() and KeyPress()):
private enum EPhase { Initiation, Countdown, MeasureTime, End }
public event PropertyChangedEventHandler PropertyChanged;
private void UpdateProperty(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
private Phase _phase;
private Phase { get { return _phase; } set { _phase = value; }
private void KeyPress(object sender, KeyEventArgs e)
{
switch (Phase)
{
case EPhase.Initiation:
{
if (e.Key == Key.Space)
{
Phase = EPhase.CountDown;
timer.SetCountdown(30);
}
break;
}
case EPhase.CountDown:
{
if (e.Key == Key.Space)
{
Phase = EPhase.MeasureTime;
timer.StopTime();
timer.ResetTime();
}
break;
}
case EPhase.MeasureTime:
{
Phase = EPhase.End;
timer.StopTime();
}
case EPhase.End: break;
}
e.Handled = true;
}
private void KeyRelease(object sender, KeyEventArgs e)
{
switch (Phase)
{
case EPhase.Initiation: break;
case EPhase.Countdown:
{
if (e.Key == Key.Space) timer.Countdown();
break;
}
case EPhase.MeasureTime:
{
if (e.Key == Key.Space) timer.StartMeasure();
break;
}
case EPhase.End:
{
if (e.Key == Key.Space) Phase = EPhase.Initiation;
break;
}
}
e.Handled = true;
}
Where The timer is an instance of my Timer class, which is my own class for handling the measurement and counting down. A Property of this class in bind to textblock of the form.
And here's the catch - I'm trying to use the e.Handled = true; to prevent the event firing in a loop while I'm holding the space key, but it doesn't happen, so i just start to hold the space but the Phase keeps looping and so it doesn't work. Anyone has an idea of what I'm doing wrong? How to solve it, please?