1

As you can see in this answer https://stackoverflow.com/a/39704027/6886308 ,you can tell when an winform was closed like in the example ,the Notepad. And I tried playing with it a bit and while the code in the example worked ,something bothered me.

What if I want to close my app when the Notepad was closed?So I tried something like:

void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
    if ((string)e.NewEvent["ProcessName"] == "notepad.exe")
        {
           Close();
        }
}

And it is trowing me an un-handled error ,so I was thinking maybe the focus remained on the winform?Or what is the problem in fact?

EDIT 1:

Here is a screenshot of the exception

Community
  • 1
  • 1
Rossalinda
  • 33
  • 7

2 Answers2

0

Your event handler is on another thread but you're calling Close on your form which isn't allowed - you need to have something like Invoke((Action)Close); which will marshall the call back to the UI thread.

auburg
  • 1,373
  • 2
  • 12
  • 22
0

You are getting the exception because you are trying to close the process from a thread other than on what it was created on. This is not allowed.

do it like this

void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
    if ((string)e.NewEvent["ProcessName"] == "notepad.exe")
        {
           this.Invoke((MethodInvoker) delegate
            {

               Close();
            });
        }
}
M. Wiśnicki
  • 6,094
  • 3
  • 23
  • 28