I imagined that WndProc is called on another thread rather than main UI thread.
I was right, so I thought that simply using InvokeRequired and Invoke on the form was enough to show a messagebox on the UI thread.
I was wrong. And I don’t understand why.
How can I go around this problem?I’m looked around google but didn’t find a solution.
What I’m trying to do is simply raising a custom event (ClipboardUpdate) when clipboard changes
the messagebox was just a test but didn’t work, while just changing something like a string (a private field of the form) works, but it’s not a good thing this behaviour because is a cross-thread operation in an unsafe way.
Update 1:
I don’t have the code here because I created it on a friend’s computer, however I can explain exactly what I wrote Because is short.
I created a basic winform with visual studio, without anything.
I used AddClipboardFormatListener (interop, but it’s quite easy as a function, return int and accept IntPtr) function (on a windows 7 OS) to just detect WM_CLIPBOARDUPDATE message, inside winproc (a simple if, *if (e.Msg == ClipboardExtension.WM_CLIPBOARDUPDATE) DoClipboardUpdate();*).
Now the DoClipboardUpdate do this:
if (InvokeRequired)
Invoke(new VoidDelegate(OnClipboardUpdate));//Void delegate it's a delegate that doesn't take
// Params and returns void
else
OnClipboardUpdate();
Quite easy right? OnClipboardUpdate just do this:
if (ClipboardUpdate != null) ClipboardUpdate(null,EventArgs.Empty);
ClipboardUpdate is an event declared in this way:
public event EventHandler<EventArgs> ClipboardUpdate;
In the end, the only method subscrived to ClipboardUpdate event has this inside:
MessageBox.Show("test");
What happens when I run the code? The event is triggered (I tried with an exception and it works) and the messagebox doesn’t popup, however I can’t interact anymore with my form because it behaves as if a popup was opened (this is the “normal” behaviour when you open a popup on a different thread, that’s why I said that).
Any suggestion on how to solve this?
I didn’t understand why it happens but I created a new project and opening a messagebox from WndProc works fine, maybe some thread corrupted main thread memory, I don’t know this but as others stated wndproc is the ui thread and should work