开发者

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.Enabl开发者_如何学Goed = false;
 }

Can anyone suggest how to make this possible?


Move the enable/disable lines in a separate method and call that method from rinxProcess_Exited using Control.Invoke method.


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


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;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜