65.9K
CodeProject is changing. Read more.
Home

.NET and COM Object Events in Console Applications

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.80/5 (2 votes)

Sep 6, 2007

CPOL

1 min read

viewsIcon

25323

downloadIcon

166

How to receive events from a COM object using the application message loop in a console application.

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:

//getting my thread ID. This is a P/Invoke call. It will get the native thread ID
id = GetCurrentThreadId();
//creating filter and delegate to run upon message ID
IMessageFilter filter1 = new MyMessageFilter(MESSAGE_TYPE_1, MyDelegate1);
//adding filter to the message loop
Application.AddMessageFilter(filter1);
//running the message loop. This call will halt till the call to Application.ExitThread()
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.
OSZAR »