views:

281

answers:

1

I'm sure this is a pretty straight forward question. I'm writing a small windows forms app using C++/CLI. When the form initializes, I start a thread that will process some code. When the code in the thread is executed, I want the thread to somehow update the text in a statusbar in the bottom of the window. So I was thinking something like this:

  1. I create an event.
  2. Then I create the Thread that will do some processing.
  3. When the processing is done, fire an event that makes the text in the statusbar update.

Is this a reasonable way to go? If so, how do I update the statusbar from within the thread? Maybe there is a smarter way to acheive this?

Would be very thankful for some advice on this.

+3  A: 

Declare a method like that changes the status text given a string:

private: void UpdateStatus(String^ msg) {
    statusBar.Text = msg;
}

and from the other thread, use Invoke:

Invoke(gcnew Action<String^>(this, &Form1::UpdateStatus), "message");

Invoke will call the given delegate with the specified parameters on the UI thread.

Mehrdad Afshari
Thank you for the help. However, first the compiler complained about Form1:UpdateStatus not being able to acces private member of Fomr1. This was solved by changing into public: void UpdateStatus(String^ msg). However, the compiler still complains about Error C2440 and Error C3754 (both are on msdn). Any advice on this?
Clean
Did you replace `Form1` with the actual class name? Are you adding both methods in the form class itself, or somewhere else (I assumed adding these snippets to the form class itself)? I just tested this in VS2008 and it works.
Mehrdad Afshari
I create an instance of another class from Form1. So when Form1 loads, i create an instance of Class B. In the EntryPoint of class B I perform some time-consuming operations. It goes like this: I start a thread from Form1 by creating an instance of class B called b, and do b -> Start(); When b is done with the time-consuming operations, I want to change the text in a statusBar that is a member of Form1. I hope this clarifies what I'm trying to do. And again, I'm really thankful that you are putting in your time to help me on this!
Clean
Why don't you use the `BackgroundWorker` class? It's designed to do this job: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Mehrdad Afshari
The BackgroundWorker did the job! I was shure there had to be an easy solution to this since it must be pretty common to do some work in the background which updates a statusbar, but I'm all new to this my knowledge was very limited. Thank you alot for your help on this!
Clean