2

I'm currently working on a project in UWP and I have a CommandBar that I want to go from Hidden to Compact if the mouse moves. After five seconds (If the mouse dont move) the CommandBar should go back to Hidden again.

I dont get any errors, but when I move the mouse the CommandBar is going crazy and it's just flashing from Hidden to Compact when I move the mouse again. I think the problem is that the OnMouseMovement event is stacking upon itself.

This is my code for the mouse movement event:

public async void OnPointerMoved(object Sender, PointerRoutedEventArgs e)
{
    CmdBar.ClosedDisplayMode = AppBarClosedDisplayMode.Compact;
    DispatcherTimer ButtonTimer = new DispatcherTimer();
    ButtonTimer.Interval = TimeSpan.FromSeconds(5);
    ButtonTimer.Tick += (sender, args) =>
    {
        CmdBar.ClosedDisplayMode = AppBarClosedDisplayMode.Hidden;
    };
    ButtonTimer.Start();
}
Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
luddep
  • 219
  • 1
  • 2
  • 14
  • 3
    Well you create new timer on every mouse move, so there are hunders of timers running which will set mode to hidden (and mouse movement sets it to compact and adds more timers). – Evk May 23 '18 at 07:56
  • Do you know any solution for that? @Evk – luddep May 23 '18 at 07:58
  • 1
    Don't create new timer on every move. Instead have one timer and reset it every time mouse moves. Also don't forget to stop that timer when it ticks, otherwise it will tick every 5 seconds, and you need just once. – Evk May 23 '18 at 08:02

1 Answers1

3

I made a little test project to try it out and get you an answer, this is what I did :

private DispatcherTimer Timer { get; set; }
public MainPage()
{
    this.InitializeComponent();
    CmdBar.ClosedDisplayMode = AppBarClosedDisplayMode.Hidden;            
    Timer = new DispatcherTimer(){Interval = TimeSpan.FromSeconds(5) };
    Timer.Tick += (sender, args) => { 
        CmdBar.ClosedDisplayMode = AppBarClosedDisplayMode.Hidden; 
        Timer.Stop();
    };

}

public async void OnPointerMoved(object Sender, PointerRoutedEventArgs e)
{
    Timer.Stop();
    CmdBar.ClosedDisplayMode = AppBarClosedDisplayMode.Compact;
    Timer.Start();            
}

Basically as @Evk said, you are creating a new timer every move of your mouse. So I declared a property for the timer and stop it then restart it when your mouse move.

Antoine Thiry
  • 2,362
  • 4
  • 28
  • 42