开发者

How to change window state of Form, on a different thread?

开发者 https://www.devze.com 2022-12-25 21:54 出处:网络
Does anyone know how I can change the window state of a form, from another thread? This is the code I\'m using:

Does anyone know how I can change the window state of a form, from another thread? This is the code I'm using:

    private void button4_Click(object sender, EventArgs e)
    {
            string pathe = label1.Text;
            string name = Path.GetFileName(pathe);
            pathe = pathe.Replace(name, "");
            string runpath = label2.Text;
            Process process;
            process = new Process();

            process.EnableRaisingEvents = true;
            process.Exited += new System.EventHandler(process_Exited);

            process.StartInfo.FileName = @runpath;
            process.StartInfo.WorkingDirectory = @pathe;
            process.Start();
            WindowState = FormWindowState.Minimized;
    }
    private void process_Exited(object sender开发者_如何学Python, EventArgs e)
    {
        this.WindowState = FormWindowState.Normal;
    }

It's meant to run a program and minimize, then return to the normal state once the program has closed. Although I get this error "Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on." Any idea how to get this to work?


This will work in .NET 3.5:

Invoke(new Action(() => { this.WindowState = FormWindowState.Normal; }));

Or 2.0:

Invoke(new MethodInvoker(delegate { this.WindowState = FormWindowState.Normal; }));


Just search this string in StackOverflow "Cross-thread operation not valid" or Google. Please, don't be that lazy.


See What’s the difference between Invoke() and BeginInvoke() on this site. The "chosen" answer gives a good explanation of what you're supposed to do.

Long story short, you want different THREADS not making a new process entirely (or highly unlikely you want that), and you probably want to use Invoke() and not BeginInvoke() which is asynchronous.


Add this line of code to the Click event handler:

process.SynchronizingObject = this;


this will solve your problem add it in the form_load event

 System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号