Aks
Aks

Reputation: 5236

WPF Non-blocking, auto-closing message box

I need to implement a non-blocking MessageBox that automatically closes after 20 seconds. Can someone suggest how I can go about doing this?

Upvotes: 3

Views: 6006

Answers (2)

xr280xr
xr280xr

Reputation: 13302

When you say non-blocking I immediately rule out the MessageBox class (assuming by non-blocking you mean a non-modal dialog?).

You can instead create a Window that is your own implementation of a MessageBox. To make it non-modal, you call the Show() method. Then you can just set up a 20 second timer to call the close method:

DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();

//Constructor
public MyMessageBox()
{
    timer.Interval = TimeSpan.FromSeconds(20d);
    timer.Tick += new EventHandler(timer_Tick);
}

public new void Show()
{
    base.Show();
    timer.Start();
}

void timer_Tick(object sender, EventArgs e)
{
    //set default result if necessary

    timer.Stop();
    this.Close();
}

The above assumes you've created a class named MyMessageBox that inherits from Window.

Upvotes: 6

Heinzi
Heinzi

Reputation: 172478

You create a new Window with a DispatcherTimer. When the window opens, you start the timer. Then you have two choices:

  • (Easy:) You set the timer to 20 seconds and close the window when the timer expires.
  • (Nice:) You set the timer to one second and decrement some counter (starting at 20) every time the timer expires. You show the counter in the window and close the window when the counter reaches 0.

Upvotes: 9

Related Questions