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(C开发者_开发百科loseCheck, 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?
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.
Probably you need to use Window.Dispatcher.Invoke
to execute the Close
method on the main UI thread.
精彩评论