Click here to Skip to main content
15,885,953 members
Articles / Programming Languages / C#

.NET and COM Object Events in Console Applications

Rate me:
Please Sign up or sign in to vote.
1.80/5 (2 votes)
5 Sep 2007CPOL1 min read 25K   166   9  
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:

C#
//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:

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader DVTel
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --