Posted by: Zeeshan Amjad | September 26, 2011

Creating WPF Application without Application class revisited


We saw one example of creating WPF application without using Application class here. In that program we called the ShowDialog method of Window class. We can do this using the Dispatcher class too by calling the Run method of dispatcher class directly. Dispatcher class maintain a priority queue for a thread. Here is a class diagram of Dispatcher class.

Dispatcher

But if we just call the run method then our program can’t terminate the thread even if we press the cross of the window. We an override the OnClosed method of the Window class and calls InvokeShutdown method. This method abort all the pending work in the queue and raise ShutdownStarted and ShutdownFinished event respectively and set HasShutdownStarted and HasShutdownFinished variable to true. Here is our complete program.

Code Snippet
using System;
using System.Windows;
using System.Windows.Threading;

namespace WpfSimple
{
    public class MyWindow : Window
    {
        public MyWindow()
        {
            Title = "WPF Window Without Application Class";
            Width = 400;
            Height = 300;
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            Dispatcher.InvokeShutdown();
        }

        [STAThread]
        static void Main(string[] args)
        {
            MyWindow win = new MyWindow();
            win.Show();
            Dispatcher.Run();
        }
    }
}

 

Here is an output of the program.

DispatcherOutput

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

Categories

%d bloggers like this: