When a call is made from VBA, C# creates an object on the MTA thread. C# Forms have to run on STA thread (this is required by some Windows Form controls) so I am creating new STA thread for the Forms. I am displaying C# form that is modal to Excel by passing Excel window handle in the ShowDialog method:
NativeWindow excelWindowHandle; ... myForm.ShowDialog(excelWindowHandle);
Problem: Most of the time this works perfectly, but sometimes C# form freezes when it is displayed for the first time (It doesn't accept mouse click or the keyboard).
Sometimes in unblocks after 1-30 seconds, sometimes more.
Switching to another application and back to C# form unblocks it always.
On some systems you can always reproduce this problem, on some almost never.
It is not up to complexity of the C# form. Problem can be reproduced for the simple forms (with a single button).
What I tried:
Microsoft support suggested that I forward WM_ACTIVATEAPP message to Excel. In "protected override void WndProc()" of the C# Form I am intercepting WM_ACTIVATEAPP and posting it (using PostMessage()) to Excel. I can confirm that C# form is not handling this message and that Excel handles posted message. This significantly lowered occurrence of the problem, but it is still there.
Microsoft support also suggested to attach input queues using the AttachInputThread(). This was only a small improvement. I understand that this function can cause deadlocks, but the problem occurs whether I use it or not. Displaying owned window should attach input queues implicitly anyway, I guess.
After some tests I started forwarding WM_CHANGEUISTATE message. #1, #2 and #3 gave the best results so far, but the problem is still observable on some systems.
Has anyone encountered this or similar problem or has any suggestions?