Dilaogs with timed self destruct

My colleague came to me today with the following question: “How can I inform the user using a MessageBox in a separate thread while the main thread continues working ?”

Since I did not found a direct answer hidden in some corner in my brain, we took a dive in internet together, found some golden fish, and cooked the following recipe:

First we create a minimalistic Form with the needed functionality for timed self destruct :

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

namespace hacks.wordpress.com
{
    public class TimedDialog : System.Windows.Forms.Form
    {
        public TimedDialog()
        {
            this.InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "I am a mission impossible message";
        }

        public void ShowTimedDialog(int time)
        {
            //{{ Setup and start the timer
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = time;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Enabled = true;
            //}}

            base.ShowDialog();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

Now we use the new created dialog in our main application

public class MainApplication
{
    public static void Main(string[] args)
    {
       Console.WriteLine("1");
       Thread mainThread = new Thread(new ThreadStart(MainApplication.startTimedDialog));
       mainThread.Start();
       Console.WriteLine("2");
       Console.WriteLine("3");

    }
    private static startTimedDialog()
    {
        TimedDialog timedDialog = new TimedDialog();
        timedDialog.ShowTimedDialog(5000);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: