How do maximize and bring a WPF mainwindow to the front of my desktop? I have a filewatcher monitoring a directory. If a new file is created in the directory I want to bring my WPF apps main window to the front of the dekstop. As you can see I have tried several methods on the mainwidnow.
Modified Code: (I am getting the following error: "The calling thread cannot access this object because a different thread owns it")
DispatcherOperation o = Dispatcher.CurrentDispatcher.BeginInvoke(new
Action(delegate
{
var win = System.Windows.Application.Current.MainWindow;
win.Activate();
win.WindowState = System.Windows.WindowState.Normal;
win.Topmost = true;
win.Focus();
}), System.Windows.Threading.DispatcherPriority.ContextIdle, null);
Debug.WriteLine("Invoke");
o.Wait();
Modified 2 (Tried getting the dispatcher of the main window. I still get " "The calling thread cannot access this object because a different thread owns it".
System.Windows.Application.Current.MainWindow.Dispatcher.Invoke(() =>
{
var win = System.Windows.Application.Current.MainWindow;
win.Activate();
win.WindowState = System.Windows.WindowState.Normal;
win.Topmost = true;
win.Focus();
}, DispatcherPriority.Normal);
UPDATE (Working) I guess I was not calling the dispatcher tied to the mainwindow with the above examples. I ended up creating a variable called _mainWindow of type MainWindow in the window class. In the MainWindow constructor I instantiated the variable: _mainwidow = this;
Then I pass the _mainwindow variable in the constructor of the class where I use the FileWatcher. Here I can access the dispatcher of the _mainwindow variable:
_mainWindow.Dispatcher.Invoke(() =>
{
var win = System.Windows.Application.Current.MainWindow;
win.Activate();
win.WindowState = System.Windows.WindowState.Normal;
win.Topmost = true;
win.Focus();
}, DispatcherPriority.Normal);
Dispatcher
of the main window instead of the current one? – Streamline