Welcome!

.NET Authors: Jim Kaskade, Adine Deford, TJ Randall, Sandi Mappic, Ivan Antsipau

Related Topics: .NET

.NET: Article

.NET Makes Window Subclassing Easy - Tap into Windows OS messages

.NET Makes Window Subclassing Easy - Tap into Windows OS messages

Imagine you are coding a .NET application that must perform some logic when a CD is inserted into the drive. Unfortunately, there is no standard event visible to your application that gets fired when a CD is inserted. Windows knows when a user puts a CD in the drive, but how can it notify your application? In fact, Windows does notify your app by sending a Windows message - your app just isn't listening for it. Subclassing gives us the ability to listen for that message and handle it appropriately. In this article, you'll learn how to use subclassing to handle the many Windows messages that are sent by the OS but not exposed through .NET's eventing model. We'll start with the basics of Windows messaging, discuss how to subclass in .NET, and finally we'll look at some more advanced techniques.

Introduction
Subclassing can be defined as intercepting window message processing in an attempt to modify the default behavior. Window subclassing gives us the ability to tap into the various messages that the Windows operating system sends and to use this ability to change our application's behavior. Windows subclassing is different from object-oriented (OO) subclassing. Windows subclassing deals with overriding a window's message handler, while OO subclassing refers to deriving a class from a base class. An implementation of Windows subclassing can be a form of OO subclassing. We'll see more about that when we discuss the various Windows subclassing implementations. But first, to truly understand Windows subclassing (hereafter referred to as simply subclassing) you must understand how the Windows operating system uses messages.

Basics of Windows Messaging
The Windows operating system is a message-based system, which means it communicates by sending messages. The OS communicates with all running applications through messages. When an application should be minimized, the OS sends a message. When an application should be closed, the OS sends a message. When a user moves a scroll bar, the OS sends a message. So what are these messages? The .NET structure created to represent a message looks like this:

public struct System.Windows.Forms.Message
{
public IntPtr HWnd { get; set;
}
public IntPtr LParam { get;
set; }
public int Msg { get; set; }
public IntPtr Result { get;
set; }
public IntPtr WParam { get;
set; }
}
The message is basically a structure used to package up and send data between windows and the OS. Let's take a look at the properties of a message:
  • HWnd: The window handle that identifies which window the message should be sent to. A window handle is basically a unique identifier for a window.
  • LParam: Contains information used to process the message. This data varies by message type.
  • Msg: Identifies the type of message that was sent.
  • Result: The return value. This is what is sent back to the OS after the message is handled.
  • WParam: Contains information used to process the message. This data varies by message type.

    If you wonder why these parameters have strange C-style names such as WParam, it's because this .NET structure is wrapping an existing C structure (MSG). Now that you understand what a message looks like, let's see how a message flows from the OS to a window.

    When a user clicks a button on a window, the mouse's device driver captures the click event. The device driver puts the event into the system message queue, which is basically a FIFO data structure set up by the OS to receive all hardware events. The OS then pulls the hardware event off the system message queue and converts it into a true Windows message. The OS then posts the message to the local message queue on the thread that is running the clicked window. The application that owns that window constantly polls the local queue for messages.

    This constant polling of the local message queue is basically a while loop that looks something like this:

    while(GetMessage(ref msg, null, 0, 0))
    {
    TranslateMessage(ref msg);
    DispatchMessage(ref msg);
    }
    This loop is built into an application by the WinForms framework. It is often referred to as the "message loop" or "message pump" because its job is to send or pump messages to the application. Let's look at some of the win32 API calls used in the message loop:
  • GetMessage: Retrieves a message from the calling thread's message queue
  • TranslateMessage: Translates virtual-key messages into character messages
  • DispatchMessage: Posts the message to the appropriate window procedure

    A message loop is required for any thread that displays a window. A message loop is created by the WinForms framework when the application code calls Application.Run. If you look at the code that is created with a new WinForms project, you'll see something that looks like this:

    static void Main()
    {
    Application.Run(new Form1());
    }
    The one line in the main method starts a message loop for the current thread and shows Form1. A message loop can be destroyed by calling Application.Exit. This method posts a WM_QUIT message to the current thread's message queue. This special message causes the GetMessage function to return false and break out of the loop.

    Now that we have a loop to retrieve messages from our thread's message queue, we have to get those messages to the appropriate window and process them. That is just what the DispatchMessage function does - it takes the message and posts it to the appropriate window. DispatchMessage uses the Hwnd associated with the message to determine which window to post the message to. To be even clearer, the DispatchMessage function actually calls a special function called the window procedure, passing in the message as a parameter. The window procedure is the function that is created to handle window messages sent to the window. It looks something like Listing 1.

    The window procedure usually consists of a big case statement. Different actions are taken depending on the window message. If a WM_PAINT is sent, the window will repaint itself. If a WM_DESTROY is sent, the window will post another message to break out of its message loop and shut down. Finally, after processing the messages, the default window procedure for the class is called. This ensures that all necessary window message handling is performed by the base window class. Subclassing consists of overriding this window procedure and providing our own custom logic to handle messages. I'll show how that is done in the next section.

    How to Subclass in .NET
    .NET truly makes subclassing easy. And for those of you used to subclassing in VB6, you no longer have to worry about General Protection Faults (GPFs) occurring if you make a mistake. In .NET there are three ways to subclass: overriding the Control.WndProc method, creating a class derived from NativeWindow, and implementing IMessageFilter. We will look at all three options, along with their pros and cons. First let's see how to override WndProc.

    One of the easiest ways to subclass in .NET is to override the WndProc method of the form you are working on. Listing 2 shows how to do this. That's it!

    .NET makes it easy for you because it exposes the virtual WndProc method on the Control class, which all windows inherit from. In order to handle a message you need to know the unique number that identifies it. The definitions for windows messages and their ID numbers can be found in the <install drive>:Program FilesMicrosoft Visual Studio .NETVc7PlatformSDKIncludeWinUser.h file. Once you know the number, it is trivial to create a constant and hook that message the way the sample code does for the double-click message. (All of the code for this article is available for download from www.sys-con.com/dotnet/sourcec.cfm.) As a side note, apart from demonstration purposes, you don't really want to show message boxes in your WndProc because that will stop the procedure from processing messages until the user clicks OK. Any messages that are not handled by your custom code are passed on to the Control's WndProc to be handled by calling base.WndProc. This allows you to handle only the messages you are interested in without having to re-implement the base Windows procedure and handle all possible messages sent to the window. The call to the base WndProc is critical, as this window will not function if key messages are not handled.

    For demonstration purposes I handled the double-click, but you may wonder what the point is of handling a message that .NET already exposes as a form event. There would be no reason to handle the double-click other than to show how subclassing works. The real power of subclassing comes from handling messages that are not exposed through the .NET eventing model. We'll look at some of those messages later, but first let's look at the second way to subclass in .NET - by using NativeWindow.

    Overriding WndProc is definitely the easiest way to subclass in .NET but it does have its drawbacks, mainly the fact that your subclassing code is now tied to one window. What if you want to use the same subclassing code on two other windows? Wouldn't it be better if you could define subclassing logic on a generic window and then use that code with other windows?

    The System.Windows.Forms .NativeWindow class does just that. It is basically an encapsulation of a Windows handle and a window procedure. It represents the roots of a window. Listing 3 shows how we use the NativeWindow class to achieve our goal of reusable message-handling code.

    Note that this code is very similar to the subclassing code shown in Listings 1 and 2. We still override WndProc, but the main difference is that we do it inside a class that inherits from NativeWindow. Remember, the NativeWindow class consists of a window procedure that we have overridden and a window handle that we assign via the AssignHandle method. We can now associate our subclassing code with any window by using the AssignHan dle method.

    There is one other way to assign subclassing code to multiple windows. We can implement the System.Windows.Forms.IMessageFilter interface. This will allow us to filter and react to all messages sent to a thread's message loop. The difference between this method and the other two is that this method intercepts messages right after they leave the thread's message loop, while the others do not intercept the messages until they are dispatched to the appropriate window. This gives us a much more global approach in that we can capture all messages sent to all windows on a thread (see Listing 4).

    Again the code looks very similar to the other examples, but instead of deriving from a base or overriding a method, we implement an interface. The one method of the interface, PreFilterMessage, passes us the message that was sent to the thread's message queue. We now have a chance to process it before this message is sent to any window. We can take action based on the message, modify it or even discard it. If the PreFilterMessage method returns true, the message is sent to the appropriate window(s). If the method returns false, then the message is discarded without being sent to any windows.

    One thing to note in regard to this method of subclassing is that not all messages go through the thread's message queue and therefore through this method. Messages can be sent in one of two ways - by being dispatched through the message queue or by being sent directly to the window and bypassing the queue. The latter type will not flow through our filter because they will go directly to the window. The way a message is sent is determined by the sender. They can use a variant of two win32 API calls:

  • SendMessage: Sends the message directly to the window
  • PostMessage: Dispatches the message to the window thread's message queue

    So the filter intercepts messages earlier than the other two subclassing methods, but as a consequence it will not receive messages that are sent directly to the window.

    Overriding WndProc is the easiest way to subclass and will intercept all messages whether posted or sent, but the subclassing code is not reusable. Inheriting from NativeWindow provides a way to receive all messages and reuse code but requires you to pass the handle of all windows whose messages should be intercepted. Finally, implementing IMessageFilter intercepts the messages for all windows created on a thread, but does not receive messages that are sent directly to the window. Now that you know the various ways to subclass in .NET, let's look at a practical example of what we can do with subclassing.

    Adding New Events Through Subclassing
    The true power in subclassing can be seen when you begin to handle messages that are not already exposed as events. For example, the DoubleClick event is already exposed as an event of a Form, but there is no event that is raised when a CD is inserted in the drive and ready for use. A good use of subclassing is to capture these kind of events that the OS communicates through Windows messages but the WinForms framework does not expose as events. Listing 5 shows how we would capture device changes such as CD inserted and removed:

    For this example we've taken the simplest approach of overriding WndProc. I want to intercept only the messages for the application's main window, so there's no need to use NativeWindow or IMessageFilter. In my overridden WndProc I simply look for the WM_DEVICECHANGE message that the OS sends to all windows when a CD is inserted or removed. I then check the message's WParam, which provides additional data about the message. In this case it specifies whether a CD was inserted or removed. That's all there is to it.

    Conclusion
    With this example, you can begin to see the possibilities of subclassing. The OS sends many messages that are not incorporated into the WinForms framework. By handling them via subclassing you can easily add new features to an application without resorting to Win32 API calls or unmanaged code.

  • More Stories By Bryant Hankins

    Bryant Hankins is a consultant at Clarity Consulting Inc., a Chicago-based information technology firm and Microsoft Gold Certified Partner. Bryant has designed and developed solutions for Fortune 500 companies in a variety of industries, including financial, accounting, and publishing.

    Comments (7)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    @ThingsExpo Stories
    SYS-CON Events announced today that AgilePoint, the leading provider of Microsoft-centric Business Process Management software, will exhibit at SYS-CON's 2nd International @ThingsExpo which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. AgilePoint is the leading provider of Microsoft-based Business Process Management (BPM) software products, has 1,300+ on-premise and cloud deployments in 25+ countries and provides the same advanced BPM feature set as J2EE vendors like IBM and Appian for the Microsoft .NET native environment. AgilePoint customer...
    Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
    The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
    SYS-CON Events announced today that TeleStax, the main sponsor of Mobicents, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. TeleStax provides Open Source Communications software and services that facilitate the shift from legacy SS7 based IN networks to IP based LTE and IMS networks hosted on private (on-premise), hybrid or public clouds. TeleStax products include Restcomm, JSLEE, SMSC Gateway, USSD Gateway, SS7 Resource Adaptors, SIP Servlets, Rich Multimedia Services, Presence Services/RCS, Diame...
    Things are being built upon cloud foundations to transform organizations. This CEO Power Panel at 15th Cloud Expo, moderated by Roger Strukhoff, Cloud Expo and @ThingsExpo conference chair, will address the big issues involving these technologies and, more important, the results they will achieve. How important are public, private, and hybrid cloud to the enterprise? How does one define Big Data? And how is the IoT tying all this together?
    We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
    The only place to be June 9-11 is Cloud Expo & @ThingsExpo 2015 East at the Javits Center in New York City. Join us there as delegates from all over the world come to listen to and engage with speakers & sponsors from the leading Cloud Computing, IoT & Big Data companies. Cloud Expo & @ThingsExpo are the leading events covering the booming market of Cloud Computing, IoT & Big Data for the enterprise. Speakers from all over the world will be hand-picked for their ability to explore the economic strategies that utility/cloud computing provides. Whether public, private, or in a hybrid form, clo...
    SYS-CON Events announces a new pavilion on the Cloud Expo floor where WebRTC converges with the Internet of Things. Pavilion will showcase WebRTC and the Internet of Things. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices--computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
    SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridsto...
    SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
    As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at Internet of @ThingsExpo, Andrew Bolwell, Director of Innovation for HP’s Printing and Personal Systems Group, will discuss how key attributes of mobile technology – touch input, senso...
    The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
    Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics...
    Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
    The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at Internet of @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., will show what is needed to leverage the IoT to transform your business. He will discuss opportunities and challenges ahead for the IoT from a market and tec...
    From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
    SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An...
    The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace.
    SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
    The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.