Click here to Skip to main content
Click here to Skip to main content

.NET and COM Object Events in Console Applications

By , 5 Sep 2007
Rate this:
Please Sign up or sign in to vote.

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.

License

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

Comments and Discussions

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