Introduction
Recently, I encountered a weird problem. I received an events dispatching COM object (which was written outside our company) which I required to integrate into the system we develop in our company. I got a nice GUI application which shows how to use the COM object (in a very easy way, I might add), and I thought to myself - "ho, how easy!" But then... it just refused to work - no events were received from it. After comparing the sample I got and a test application I made, I found out that the COM object only dispatches events when a message loop exists. So, I had to have a message loop for dispatching events, and I had to use that thread to call functions in that COM object too. Here is a sample for a possible solution.
Background
A message loop takes a thread, the one that calls the Application.Run
function. The communication with this message loop can be done by a posting to the message loop. In a GUI thread, it can be easily done using the BeginInvoke
function which is available in the Control
class. In a console application, it's a bit harder, and you need to use P/Invoke for posting and to find the current message loop ID.
Using the Code
Creating the message loop thread:
id = GetCurrentThreadId();
IMessageFilter filter1 = new MyMessageFilter(MESSAGE_TYPE_1, MyDelegate1);
Application.AddMessageFilter(filter1);
Application.Run(new ApplicationContext());
Sending messages to the application loop:
PostThreadMessage(id, MESSAGE_TYPE_1, UIntPtr.Zero, IntPtr.Zero);
Points of Interest
I found a very nice site called PInvoke.NET. It helped in locating and defining the P/Invoke declarations correctly.
History
- 6-Sep-2007: First release.