title: How can I bring the main WPF window to the front?
body: <p>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.</p>
  
  <p>Modified Code: (I am getting the following error:  "The calling thread cannot access this object because a different thread owns it")</p>
  
  <pre><code>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();
  </code></pre>
  
  <p>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".</p>
  
  <pre><code> System.Windows.Application.Current.MainWindow.Dispatcher.Invoke(() =&gt;
      {
          var win = System.Windows.Application.Current.MainWindow;
          win.Activate();
          win.WindowState = System.Windows.WindowState.Normal;
          win.Topmost = true;
          win.Focus();
      }, DispatcherPriority.Normal);
  </code></pre>
  
  <p><strong>UPDATE (Working)</strong>
  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;</p>
  
  <p>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:</p>
  
  <pre><code>        _mainWindow.Dispatcher.Invoke(() =&gt;
          {
              var win = System.Windows.Application.Current.MainWindow;
              win.Activate();
              win.WindowState = System.Windows.WindowState.Normal;
              win.Topmost = true;
              win.Focus();
          }, DispatcherPriority.Normal);
  </code></pre>