Search code examples
c#windowspinvoke

When is WindowProc called?


In my C# program using P/Invoke I change the procedure address for my window. So I can react to windows messages I'm interested in.

But when is the procedure called by the System? I have Lists that I manipulate both in my custom procedure, and in the rest of my code. How does the system decide when it can or can't call the procedure, and is there a chance that data can be corrupted?

e.g.

I add entries to a list in my procedure.

I read-through the list and process the entries in another part of my code.

Before I manage to clear list, the procedure takes over and adds more entries.

Return back to the other part of my code, the list is cleared and the new entries are discarded without being processed.


Solution

  • You probably shouldn't be using p/invoke to do this, as it can interfere with the way Windows Forms (or WPF) manage the message pump.

    If you must, you can try these approaches: Setting up Hook on Windows messages

    Or you can override WndProc in your main form class, which needs no further explanation.