A common and safe method used to initiate an update to the UI from a non-UI thread is to use a custom window message. The non-UI thread is passed the HWND of the window that handles updating on the UI thread. In your example you could use the pCallbackContext parameter to pass the HWND when you register the callback. The callback function will receive the HWND as one if its parameters. Inside the callback, use PostMessage to post the custom window message to the HWND. You would need to include code in your Winform project to recognize the custom window message and update the UI, typically with a WndProc override.
Invoking functions from a non-managed thread
Hello! I was wondering if it is possible to Invoke/BeginInvoke a delegate from a non-managed thread.
To elaborate, I've got a Windows Forms... form which contains a little image (PictureBox object) that indicates the current state of the PC's Wi-Fi connection (online/offline).
I have registered a callback function using the WlanRegisterNotification function from the Native Wi-Fi API. Whenever the network connection state changes, my callback is executed (on a different thread, if I remember correctly) and I get the new connection state in one of the callback function parameters.
I was wondering if I could immediately BeginInvoke a delegate on my form from the callback function in order to change the image displayed in my PictureBox, but I remember vague warnings from various sources which recommend against mixing managed thread and non-managed thread code. I could not find any source that addresses my example in detail, though, and I'm having trouble deducing why my example could be a bad idea.
Has anyone attempted something like this?
1 additional answer
Sort by: Most helpful
-
Ken Tucker 5,851 Reputation points
2021-06-26T23:49:05.497+00:00 You could try using a dispatch timer. when the network status needs to be changed set a property that you look for in the dispatch timer tick event. If it is set change the image