5 December 2011

Handling System Shutdown / Logoff events in C#.NET

On .NET forums, I often come across people interested in knowing about notifications of something changed in the system. For example whether windows is shutting down, whether user is logging off, power mode changed, or system font changed etc. For instance, you may want to perform some operation when your application is terminating. In that case, what are all the possible ways of terminating the application?
  1. Closing the application by clicking close 'x' button
  2. Due to exception
  3. User kills the process
  4. When the user logs off or system shuts down
The first 2 are common scenarios which the user can take care of easily. But what about the 3rd and 4th cases? The 3rd case is, I don't think we can control. However, 4th one is interesting. When the system shutdown is started either by user or by any automated process, the shutdown process will terminate all running processes. Before that it sends a signal to all running processes that the system is going to shutdown. Upon receiving this signal, a process can do any windup operation so as to prevent any data loss. This is very important because you might be in middle of some important operation and sudden application termination may cause valuable data loss.

So, how do a .NET application receives this signal? Whenver it comes to the matter of system related things, many people think of native OS DLLs or PInvoke (some unmanaged way). But wait, we have some managed objects that do the work. There is a class called SystemEvents in Microsoft.Win32 dll which offers many system based events. You can google or refer MSDN for more info SystemEvents class. Here, I will just take an example of how System shutdown or user logoff events are handled.

Below is a simple console application that displays a message box whenever a system shutdown occurs or user logs off (In any case, it causes CLR to unload and hence a notification is sent about the event).

class Program
{
    static void Main(string[] args)
    {
        SystemEvents.SessionEnding += SystemEvents_SessionEnding;
        Console.ReadLine();  //This is needed to keep the application running.
    }

    static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
    {
        switch (e.Reason)
        {
            case SessionEndReasons.Logoff:
                MessageBox.Show("User logging off");
                break;

            case SessionEndReasons.SystemShutdown:
                MessageBox.Show("System is shutting down");
                break;
        }
    }
}

46 comments:

  1. This works only if the application is run by the logged on user. Otherwise it is not working.

    ReplyDelete
  2. From my limited understanding, it's possible to get around that by having a service with a hidden form so that the hidden form receives the notification like any other window so the user shouldn't matter... but I'm no coder so that could be complete bollocks. If it doesn't work that way, it should!

    Pat

    ReplyDelete
  3. Can i Cancel shutdown programmatically??? Need it hard

    Whole scenario is that I have evolution period of Win Server 2012 that restarts automatically after 1 hour, I want to override this behavior.

    ReplyDelete
  4. I am not sure of that. However, try executing below command.
    Process.Start("shutdown", "-a")

    ReplyDelete
  5. Thanx for quick response.........

    But that does not work for me ;-(

    ReplyDelete
  6. its not working on the windows 8 pc

    ReplyDelete
  7. Thanks for sharing wonderful blog. For .net training

    ReplyDelete
  8. Hai Author Good Information that i found here,do not stop sharing and Please keep updating us..... Thanks.
    hire asp.net developer
    .net development services

    ReplyDelete
  9. Thanks for sharing wonderful blog. But it works only when user is login except not work. Try to got .Net Training

    ReplyDelete
  10. It 's an amazing article and useful for developers
    .Net Online Training

    ReplyDelete
  11. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    python training in tambaram
    python training in annanagar
    python training in velachery

    ReplyDelete
  12. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    python training in chennai
    python training in chennai

    ReplyDelete
  13. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ReplyDelete
  14. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    angularjs Training in chennai
    angularjs-Training in pune

    angularjs-Training in chennai

    angularjs Training in chennai

    angularjs-Training in tambaram

    ReplyDelete
  15. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.


    AWS Training in BTM Layout |Best AWS Training in BTM Layout

    AWS Training in Marathahalli | Best AWS Training in Marathahalli


    Selenium Interview Questions and Answers

    AWS Tutorial |Learn Amazon Web Services Tutorials |AWS Tutorial For Beginners

    ReplyDelete
  16. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.


    AWS Training in BTM Layout |Best AWS Training in BTM Layout

    AWS Training in Marathahalli | Best AWS Training in Marathahalli


    Selenium Interview Questions and Answers

    AWS Tutorial |Learn Amazon Web Services Tutorials |AWS Tutorial For Beginners

    ReplyDelete
  17. Awesome..You have clearly explained.it is very simple to understand.it's very useful for me to know about new things..Keep posting.Thank You...
    aws online training
    aws training in hyderabad
    aws online training in hyderabad

    ReplyDelete
  18. Good job! Fruitful article. I like this very much. It is very useful for my research. It shows your interest in this topic very well. I hope you will post some more information about the software. Please keep sharing!!
    SEO Training in Chennai
    SEO Training
    SEO Course in Chennai
    Digital Marketing Course in Chennai
    Digital Marketing Course
    Digital Marketing Training in Chennai

    ReplyDelete
  19. Hyderabad Events Website gives complete information of upcoming events,food festivals,science conferences,youth seminars,movie summits & fashion programs.Watch Today!
    https://www.hyderabadevents.com/

    ReplyDelete
  20. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training

    ReplyDelete
  21. Hey Nice Blog!! Thanks For Sharing!!! Wonderful blog & good post. It is really very helpful to me, waiting for a more new post. Keep Blogging ! Here is the best angularjs training online with free Bundle videos .

    contact No :- 9885022027.
    angular js training

    ReplyDelete
  22. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration

    ReplyDelete
  23. By presenting your skill and technical knowledge getting the increment also makes the path to your bright job career. cursos de ti online

    ReplyDelete
  24. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing...

    sap business intelligence training

    ReplyDelete
  25. Thanks for sharing such a great information..Its really nice and informative..

    learn sap ui5

    ReplyDelete

  26. This is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious.

    sap bw on hana training

    ReplyDelete
  27. This is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious. azure course

    ReplyDelete
  28. azure tutorial This is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious.

    ReplyDelete
  29. I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this sharepoint training , I feel happy about it and I love learning more about this topic.

    ReplyDelete
  30. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
    Artificial Intelligence Certification Course
    Java Certification Course
    AWS Certification Course
    Machine Learning Certification Course
    Data Science Certification Course
    DevOps Certification Course

    ReplyDelete
  31. I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
    Java Training in Chennai

    Java Training in Velachery

    Java Training inTambaram

    Java Training in Porur

    Java Training in Omr

    Java Training in Annanagar

    ReplyDelete
  32. Very nice blogs!!! i have to learning for lot of information for this sites…Sharing for wonderful information. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing,
    Software Testing Training in Chennai

    Software Testing Training in Velachery

    Software Testing Training in Tambaram

    Software Testing Training in Porur

    Software Testing Training in Omr

    Software Testing Training in Annanagar

    ReplyDelete
  33. Great article with very unique and useful information,,,
    Thank you,,,,Keep Updating,,,

    Power BI Online Training Hyderabad

    ReplyDelete
  34. Great information about wilderness for beginners giving the opportunity for new people. My Chemical Romance Jetstar Jacket

    ReplyDelete