Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing form from another thread

I have got this code which runs an .exe

string openEXE = @"C:\Users\marek\Documents\Visual Studio 2012\Projects\tours\tours\bin\Debug\netpokl.exe";
                 Process b = Process.Start(openEXE);
                 b.EnableRaisingEvents = true;
                 b.Exited += (netpokl_Closed);

And when it closes it calls method netpokl_Closed. The issue is when I insert into netpokl_Closed command - this.Close() this exception rises: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

How can I fix it ? Thank you for your time and answers.

like image 662
Marek Avatar asked Aug 19 '13 08:08

Marek


People also ask

How do I close one form from another?

You can use the following code to close one FORM from another FORM in C# Winform Application. FrmToBeClosed obj = (FrmToBeClosed)Application. OpenForms["FrmToBeClosed"]; obj. Close();

How do you make a form close?

You can close a Google Form at any time when you don't want to receive further responses. To close your Google Form, click on the Responses tab and toggle the "Accepting responses" option off.

How do I close Form1 and Form2?

Solution 1 If Form1 is the main form for the application, then closing it will end the application, closing Form2 as well. Form2 f2 = new Form2(); Hide(); f2.


2 Answers

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

do it like this

this.Invoke((MethodInvoker) delegate
        {
            // close the form on the forms thread
            this.Close();
        });
like image 101
Ehsan Avatar answered Sep 20 '22 07:09

Ehsan


When a thread other than the creating thread of a control tries to access one of that control's methods or properties, it often leads to unpredictable results. A common invalid thread activity is a call on the wrong thread that accesses the control's Handle property

Gets or sets a value indicating whether to catch calls on the wrong thread that access a control's Handle property when an application is being debugged.

have a look at

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.checkforillegalcrossthreadcalls.aspx

like image 20
Andrew Avatar answered Sep 22 '22 07:09

Andrew