C#.NET : Updating a UI component from another thread

I've working on an application that needed to create another thread. My problem is how to update my UI component from another thread?

Inside your form class declare this as member,

public
delegate
void
InvokeDelegate(string input);


 

then create a function that as call-back like below,

public
void UpdateLog(string input)

{

            this.tbTestMessage.Text = input;

            this.btWaitForDrawerClose.Enabled = m_boolWaitButtonState;

}


 

Okay, now how will you be able to call the function? Inside your thread make the code below,

object[] obj = new
object[1];

obj[0] = m_strTestMessage;

this.tbTestMessage.BeginInvoke(new
InvokeDelegate(UpdateLog), obj);


 

tbTestMessage is a textbox control. So, below is the complete code


 

class MyForm : Forms

{

Public delegate void InvokeDelegate(string input);

MyForm()

{

}

Public void UpdateLog(string input)

{

this.tbTestMessage.Text = input;

}


 

//this function is executed by another thread

Void MyOtherThread()

{

Object[]obj = new object[1];

Obj[0] = m_strTestMessage;

tbTestMessage.BeginInvoke(new InvokeDelete(UpdateLog, obj);

}

}


 

That's it!


 

Comments

Post a Comment

Popular posts from this blog

Digital Logic

Visual Studio 2008 MFC: How to embed a dialog to a dialog

How to statically link applications to wxWidgets via Visual Studio 2008 and in Linux