简体   繁体   中英

How to enable form button after process has exited?

I have an windows application developed using C#. In this application, I am creating one process. I want to enable and disable few buttons when Process_Exited() event occures. In Process_Exited() method, I have written code to enable buttons but at runtime I get error as

"Cross-thread operation not valid: Control 'tabPage_buttonStartExtraction' accessed from a thread other than the thread it was created on."

My code snippet is :

 void rinxProcess_Exited(object sender, EventArgs e)
 {
     tabPage_buttonStartExtraction.Enabled = true;
     tabPageExtraction_StopExtractionBtn.Enabled = false;
 }

Can anyone suggest how to make this possible?

在单独的方法中移动启用/禁用行,并使用Control.Invoke方法从rinxProcess_Exited调用该方法。

You must make UI changes on the UI thread. See this question for more details.

Here's the solution applied to your example:

void rinxProcess_Exited(object sender, EventArgs e)
{
    if (this.InvokeRequired)
    {
        this.Invoke((Action)(() => ProcessExited()));
        return;
    }

    ProcessExited();
}

private void ProcessExited()
{
    tabPage_buttonStartExtraction.Enabled = true;
    tabPageExtraction_StopExtractionBtn.Enabled = false;
}

You're attempting to change the UI from a different thread. Try something like this;

    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.textBox1.InvokeRequired)
        {   
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.textBox1.Text = text;
        }
    }

You shouldn't be doing much work on the UI from another thread, as the invocations are quite expensive.

Source: http://msdn.microsoft.com/en-us/library/ms171728.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM