Core-One
Core-One

Reputation: 476

closing a window on a timer

Functionality that I need: A WPF modeless window needs to close when a window of a third party appliction is closed. Now, I have no problem with the 3rd party app, using some PInvoke for this.

using System.Threading;
public partial class MyWindow : Window
{
    public MyWindow()
    {
        InitializeComponent();

        Timer T = new Timer(CloseCheck, this, 1000, 1000);
    }


    public void CloseCheck(object o)
    {
        MyWindow  w= (MyWindow)o;

        // left out all the PInvoke  condictional code to simplyfy

        w.Close();
    }
}

If you run this code it's just a quick way to kill your total application. I think it has to do with threading, but how would I implement things the right way?

Upvotes: 0

Views: 2127

Answers (2)

brunnerh
brunnerh

Reputation: 184524

You need to use the Dispatcher to access DependencyObjects from a different thread. You could also use a DispatcherTimer instead of a normal timer which encapsulates it.

Also see the threading model reference.

Upvotes: 1

Uwe Keim
Uwe Keim

Reputation: 40736

Probably you need to use Window.Dispatcher.Invoke to execute the Close method on the main UI thread.

Upvotes: 0

Related Questions