?
Solved

How to close application form from another Thread in C# .NET?

Posted on 2007-03-28
3
Medium Priority
?
2,091 Views
Last Modified: 2013-12-17
I have two forms, I am running some worker events on a thread in form A, when that work is done I want to close Form A and show Form B.  

If I simply use this.hide() I receive a cross thread exception which makes sense because I am not accessing it from the same thread.  Is this even possible?

private void CreateWorkerThread()
        {
            //Instance a ThreadStart object and intance it with the SnapShot class CollectData method.
            ThreadStart _threadStartA = new ThreadStart(DoWork);
            //Initialize a Thread object and set to null;
            Thread _threadA = null;


            try
            {
                //Instance Thread object with ThreadStart object.
                _threadA = new Thread(_threadStartA);
                //Name the Thread
                _threadA.Name = "Phase1";
                //Spawn the Thread
                _threadA.Start();
            }
            catch (Exception exp)
            {
                MessageBox.Show("Image Apply error: " + exp.Message);
            }
        }
        private void DoWork()
        {
            Test.com.Recovery.Recovery oRecovery = new Test.com.Recovery.Recovery();

            //Hook command line events
            oRecovery.OnCmdStarted += new Test.com.Recovery.RecoverCommandStarted(oRecovery_OnCmdStarted);
            oRecovery.OnCmdExited += new Test.com.Recovery.RecoverCommandExited(oRecovery_OnCmdExited);
            oRecovery.OnCmdOutputLine += new Test.com.Recovery.RecoveryCommandOutputLine(oRecovery_OnCmdOutputLine);

            //Hook image events
            oRecovery.OnStarted += new Test.com.Recovery.RecoverStartedEventHandler(oRecovery_OnStarted);
            oRecovery.OnComplete += new Test.com.Recovery.RecoverCompleteEventHandler(oRecovery_OnComplete);
            oRecovery.OnProgress += new Test.com.Recovery.RecoverProgressEventHandler(oRecovery_OnProgress);
            oRecovery.OnProcess += new Test.com.Recovery.RecoverProcessEventHandler(oRecovery_OnProcess);
            oRecovery.OnError += new Test.com.Recovery.RecoverErrorEventHandler(oRecovery_OnError);

           
            //First we need to get a DiskPart object
            if (oRecovery.ConfigureDisk(PopulateDiskPart(), true))
                if (oRecovery.RecoverImage(PopulateImage(ImageType.Debug)))//Recover 1st image first
                    if (oRecovery.RecoverImage(PopulateImage(ImageType.Debug)))//Recover 2nd image last
                    {
                                         this.Hide() <--- BAD wont work cross thread exception.
                        ***** DONE CLOSE THIS FORM AND OPEN A NEW FORM
                    }
        }
0
Comment
Question by:yami_rider
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 11

Expert Comment

by:Babycorn-Starfish
ID: 18812652
Hi,

what owns the instance of FormA?
0
 

Author Comment

by:yami_rider
ID: 18812717
Maybe I should go into more detail about this.  Actually I am creating an application with several forms.

1. 3 Forms
a. First form is a end user license agreement with two buttons (agree and cancel)
b. Second form is will be displayed to the user showing the recovery process.  This has a progress bar.
c. Last form is simply a form that tells the user the recovery is complete or not complete.

If you can think of a setup application where the user is brought through multiple forms that is what I am trying to achieve.

When the EULA is displayed and the user clicks on agree I want the EULA form to disappear and the
Second form to appear and begin the recovery. When the recovery completes, I want the second form to close and the final form displaying that the recovery is complete or not complete to appear.

In the second form since I have controls on it and I am doing some background operations I spawn a thread and safely invoke the update on the controls (i.e. progress bar, etc.). This is where I think my problem is.
0
 
LVL 11

Accepted Solution

by:
Babycorn-Starfish earned 750 total points
ID: 18812898
Its probalby a hacky way of doing it but off the top of my head (though there are bound to be countless examples on this site somewhere and hopefully someone will step in....)

1) I'd make one form the main one (the one that gets shown after you accept the EULA)
In this form's Load event i'd create and show the form with the eula on.

2) on the EULA form i'd assign Ok and cancel repsectively to the Dialog Result property for eachg of the two relevant buttons for accepting or declining the EULA

3) when the user clicks either button close the form and retunr to the main form, then check the dialog result, e.g

        private void Form1_Load(object sender, EventArgs e)
        {
            Form2 eula = new Form2();
            eula.ShowDialog();
            if (eula.DialogResult == DialogResult.OK)
            {
                MessageBox.Show("Thanks for agreeing");
                //do your other stuff
             }
            else
                Close();
        }
Form here i'd do my business in a separate thread using a delegate and the forms Invoke function to update a progress bar and such like then hide the main form and show the final form upon completion of all my background tasks. When you close the third form the line after the one that showed it should be Close() to exit the app.
0

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question