Search code examples
c++multithreadingwxwidgets

Use wxthread to update content of wxframe in C++


I am a newbie in using threads. I have developed a program in C++ using wxwidgets to show the count of packets received through the network interface. What I have done so far is: I have a wxbutton in a wxdialog. On clickng on the button a wxframe containing wxgrid is opened. The wxgrid contains info like interface name, packets in and packets out.

Now what I need is to constantly update the packets in and packets out fields. I have a function that calculates the packets in and packets out. So I think I need to execute the function continuously until the user closes the frame.

I hope wxthread can be utilized to perform this. But have no idea on how to start with or how a function can be executed from a thread. Can someone please guide me.. THANK YOU


Solution

  • A worker thread can't access any GUI object directly, so you need to post events to the main thread where you can define event handlers for them which will do whatever you need. There is a convenient base class for such events called wxThreadEvent that you may find useful.

    Alternatively, and especially if you use C++11, you could use CallAfter() which allows you to execute a callback in the main thread context. This is especially nice with C++11 lambdas because it allows you to keep all your code in the same place without having to extract it into a separate event handler.