0

I have an image control in my WPF (it's basically the whole window). When the user makes a wrong input I want the image to change and then even shake the screen, wait a second (with Thread.Sleep()) and then change the image back to the original one.

The problem is: Even though I change my image in my function before shaking the screen, it still get's changed after all functions are executed.

How can I archieve my goal?

This is what I tried:

                    //Change Diary Background
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.UriSource = new Uri(System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) + @"\lib\ViewLogin\ViewLoginIncorrect.png");
                    bitmap.EndInit();
                    imgDiary.Source = bitmap;

                    Thread.Sleep(1000);

                    //Shake Screen
                    this.Left = this.Left - 20;
                    Thread.Sleep(50);
                    this.Left = this.Left + 20;

                    txtMasterKey.Focus();

And only after everything is done my image changes. Image example

  • Thread.Sleep blocks the UI thread. Declare your method `async` and replace `Thread.Sleep(...)` by `await Task.Delay(...)`. – Clemens May 14 '19 at 16:38

1 Answers1

-1

Thread.sleep blocks the ui thread, which is the thread that would change any ui

That is your problem.

Make your method async.

Replace thread.sleep(n) with await task.delay(n).

Where n is the numbers you have there.

Andy
  • 11,864
  • 2
  • 17
  • 20