Microsoft Cloud Authors: Janakiram MSV, Yeshim Deniz, David H Deans, Andreas Grabner, Stackify Blog

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

Catching SENS Events in .NET

Keep tabs on Windows with System Notification Events

To register for the SensLogon events, we need to implement the ISensLogon interface, with its required methods. In .NET we usually use delegates and events for notification. To translate between the COM method calls and the .NET events we would rather have, we need a structure to mask the old COM code.

When another programmer imports this library, we only want my .NET-friendly classes and events to be exposed. The main class we will expose is called SensLogon, and will have static events for logon, screen lock, etc. To directly receive the messages and then raise the events, this class would need to implement the ISensLogon interface, but that would expose the methods of the interface to anyone, allowing other code to fake the events. To prevent this, we will create a private inner class called SensLogonInterop to implement and hide the interface, register for the events, and forward the events to the containing class. Some of the code for this implementation is in Listing 4 (though much of the code is removed for brevity, it is very similar to what is shown).

The SensLogonInterop class has a few constant and static values at the top for registering with the COM+ Event System. These members are used in the class constructor to register it with the Event System. Since it is a private inner class, it can only be instantiated by the SensLogon class. The SensLogon class keeps a static reference to the only instance, thus preventing it from being garbage collected.

Once we have a class that will get the events raised by the SENS Events system, we need to add events to the SensLogon class so that it can raise them. This is the trickiest part. COM interoperability is slow, so if no classes within an application are registered to events, we do not want COM to send them. For efficiency, we need a system that registers with COM when a class first registers with SensLogon and removes the COM registration when no classes are left.

The typical way of declaring an event in a C# class is inadequate because we cannot perform any special processing when a delegate is attached to an event. Thankfully, C# provides a way of creating custom event registration code: write an event as though you are writing a property, but use the add and remove keywords instead of get and set. The add keyword is for when a delegate is attached to the event, and the remove keyword is for when a delegate is detached from the event. This is illustrated at the bottom of Listing 5. It takes more work to attach and detach events, but because of the RegisterEvent and UnregisterEvent routines, it is a lot simpler than it could have been.

Also, to actually raise the events, we have protected static OnEventName methods, which are used to raise the events defined (having a protected method that raises an event is standard procedure for all events in the .NET Framework). The appropriate method is called by the SensLogonInterop class when an event comes in, thereby causing the associated event to be raised, if anyone is registered for that event.

Bringing It All Together
Now we get back to the initial problem: getting an event whenever someone locks or unlocks their screen. In the DotNetSENS Console project, add a reference to the ManagedSENS project. Then, the code should change to the code in Listing 6. This is very similar to the code in Listing 1, but it uses our new .NET class for catching the SENS event. From start to finish, these are the steps to catch the screen lock and screen unlock events.

  1. The application starts up, and the DisplayLock event has a delegate attached to it
  2. This attachment causes the SensLogon class to create an instance of the SensLogonInterop class
  3. The SensLogonInterop class registers for the ISensLogon events with the COM+ Event System
  4. The application then attaches to the DisplayUnlock event, which does nothing other than remember the delegate to call
  5. The application then waits for the user to hit the enter key before quitting
  6. Meanwhile, when the screen is locked, SENS sends the event out to the COM+ Event System
  7. The COM+ Event system passes the event to the instance of SensLogonInterop by calling DisplayLock
  8. When DisplayLock is called, it calls SensLogon.OnDisplayLock
  9. OnDisplayLock then raises the DisplayLock event
  10. The application catches the event, and writes out to the console my login name
  11. When the screen is unlocked, steps similar to steps 6 through 10 are run
Although it takes a lot of work to register for COM+ Events, there is a lot of information that can be gained from them. Once set up in an appropriate way, all of this code can be masked from future users so that attaching to and catching these events is seamless to a .NET application.

SENS Events in .NET 2.0
In .NET 2.0, Microsoft provides some events that look similar to SENS events (http://winfx.msdn.microsoft.com/library/ en-us/cpref/winfx/ref/microsoft.win32.asp?frame=true). These events are actually provided through messages sent to a Window's main message handler, the WndProc method. Through P/Invoke, you can register for these messages, and receive them in .NET 1.1 or you can attach to the events provided in .NET 2.0 (check out the documentation in MSDN about WTSRegisterSessionNotification for information on these messages). Unfortunately, no messages are sent when the screen saver starts and stops. Also, these messages do not provide any information about the account that caused them.

More Stories By Richard Arthur

Richard Arthur is currently an instructor of C# at Northface University (www.northface.edu) in Salt Lake City, Utah. He has gained extensive experience doing Automation of MS Office products through VBA and COM at previous jobs.
In his spare time he learns about the inner workings of many current and future .NET Technologies, including Windows Forms, ASP.NET, Generics, P/Invoke, and COM Interoperability.
If anyone has any questions regarding this article, please contact Richard at [email protected]

Comments (0)

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
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
In a recent survey, Sumo Logic surveyed 1,500 customers who employ cloud services such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). According to the survey, a quarter of the respondents have already deployed Docker containers and nearly as many (23 percent) are employing the AWS Lambda serverless computing framework. It’s clear: serverless is here to stay. The adoption does come with some needed changes, within both application development and operations. Tha...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
Amazon is pursuing new markets and disrupting industries at an incredible pace. Almost every industry seems to be in its crosshairs. Companies and industries that once thought they were safe are now worried about being “Amazoned.”. The new watch word should be “Be afraid. Be very afraid.” In his session 21st Cloud Expo, Chris Kocher, a co-founder of Grey Heron, will address questions such as: What new areas is Amazon disrupting? How are they doing this? Where are they likely to go? What are th...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they b...
SYS-CON Events announced today that SkyScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SkyScale is a world-class provider of cloud-based, ultra-fast multi-GPU hardware platforms for lease to customers desiring the fastest performance available as a service anywhere in the world. SkyScale builds, configures, and manages dedicated systems strategically located in maximum-security...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
Organizations do not need a Big Data strategy; they need a business strategy that incorporates Big Data. Most organizations lack a road map for using Big Data to optimize key business processes, deliver a differentiated customer experience, or uncover new business opportunities. They do not understand what’s possible with respect to integrating Big Data into the business model.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.