Search code examples
wpfmultithreadingnotifyicon

How to hide a window using another thread?


I've create a WPF application with NotifyIcon, and I use this.Hide() to make it minimized, but now I hope it could be minimized once it had been executed, so I invoke this.Hide() in the method MainWindow_Loaded, but once I start the app, the content of the window turn to be all dark.

Then I try to invoke this.Hide() in another thread, and this is what my code looks like...

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
...
   Thread thread = new Thread(DoWork);

   thread.Start();
   Console.WriteLine("thread start");

   while (!thread.IsAlive) ;

   Thread.Sleep(500);

   thread.Join();
   Console.WriteLine("thread has terminated.");
...
}

public void DoWork()
{
    this.Hide();
}

then I encounter the problem, when DoWork() is invoked, it showed Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on. What should I do to avoid this? Thanks!


Solution

  • You need to use Dispatcher object.

    Dispatcher.BeginInvoke((Action) (() =>
        {
            // your code
        }));