Click here to Skip to main content
13,299,495 members (71,190 online)
Click here to Skip to main content
Add your own
alternative version


9 bookmarked
Posted 6 Sep 2007

.NET and COM Object Events in Console Applications

, 6 Sep 2007
Rate this:
Please Sign up or sign in to vote.
How to receive events from a COM object using the application message loop in a console application.


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.


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
//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.


  • 6-Sep-2007: First release.


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


About the Author

Boaz V
Team Leader DVTel
Israel Israel
No Biography provided

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171207.1 | Last Updated 6 Sep 2007
Article Copyright 2007 by Boaz V
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid