0

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!

Bono
  • 4,757
  • 6
  • 48
  • 77
Alanight
  • 353
  • 2
  • 8
  • 23
  • Why do you want to `Hide()` your window from another thread? What's the point in this? – dymanoid Jan 16 '15 at 08:36
  • Because I need to hide the window immediately once I start my computer, I invoke Hide() in the MainWindow_Loaded, but it cause my window show nothing but a filled with dark, and that's the reason why I want to do it in this way. – Alanight Jan 16 '15 at 08:47
  • You should find out why your window does get black rather than invent any multithreading workarounds. I suppose there's something wrong with your code. Your question is a typical [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – dymanoid Jan 16 '15 at 08:53
  • Yeah! At first I invoke Hide() in other place, and it works without any problem; but after I invoke it it MainWindow_Loaded, the problem just happened, but i really NEED to invoke Hide() in MainWindow_Loaded, because I have to minimize my app once the computer has start. Thanks for your advice! I'll learn to clear my question before I search another way to solve it. – Alanight Jan 16 '15 at 10:01

1 Answers1

1

You need to use Dispatcher object.

Dispatcher.BeginInvoke((Action) (() =>
    {
        // your code
    }));
Mahesh Malpani
  • 1,782
  • 16
  • 27