Tuesday, February 22, 2011

WPF - Lock,Shutdown,Restart and Log off the system in WPF

This article is about locking, logging off , restarting, shutting down the system in WPF.Here we are going to use both unmanaged code and .Net framework for these functions.

Step 1
Create a WPF Application.

Step 2
Add a four buttons entitled btnLock,btnShutDown,btnRestart,btnLogOff on window,it is look like this


<Window x:Class="SolShutdown.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Lock" Height="53" HorizontalAlignment="Left" Margin="76,129,0,129" Name="btnLock"  Width="75" Click="btnLock_Click" />
        <Button Content="ShutDown" Height="53" HorizontalAlignment="Left" Margin="171,129,0,129" Name="btnShutDown" Width="75" Click="btnShutDown_Click" />
        <Button Content="Restart" Height="53" HorizontalAlignment="Left" Margin="267,129,0,129" Name="btnRestart" Width="75" Click="btnRestart_Click" />
        <Button Content="Log Off" Height="53" HorizontalAlignment="Left" Margin="359,129,0,129" Name="btnLogOff" Width="75" Click="btnLogOff_Click" />
    </Grid>
</Window>

Step 3
Add a System.Management assembly reference to the project from solution explorer,it is look like this





















Step 4
Lock Workstation

Let us start with locking the workstation, which is supposed to lock the current user session. We will call a windows API for doing this. For calling an unmanaged code, we need to add the System.Runtime.InteropServices namespace to the using directive.


using System.Runtime.InteropServices;



Import the windows API library and define the function that we intend to use. The function to lock the workstation resides in the user32.dll library. And the function for locking the desktop is LockWorkStation. The following statements should be added to the class to import the library.


 #region Window API

        [DllImport("user32.dll")]
        public static extern void LockWorkStation();

 #endregion

Step 5
Double click the btnLock button to create a click event handler and call the LockWorkStation API to lock the workstation,it is look like this.


private void btnLock_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to Lock your computer?", "Lock Computer", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    LockWorkStation(); 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

Step 6
Write a method for shutdown,restart and log off windows,it is look like this

  #region Methods

        /// <summary>
        ///  Shutdown,restart and log off Computer
        /// </summary>
        /// <param name="Flags">Specify the Shut down Parameter
        ///  "1" - Shut down
        ///  "2" - Restart
        ///  "0" - Log off
        /// </param>
        private void ShutDownWindows(String Flags)
        {
            try
            {
                ManagementBaseObject MBOShutdown = null;
                ManagementClass MCWin32 = new ManagementClass("Win32_OperatingSystem");
                MCWin32.Get();

               
                MCWin32.Scope.Options.EnablePrivileges = true;
                ManagementBaseObject MBOShutdownParams = MCWin32.GetMethodParameters("Win32Shutdown");
                
                MBOShutdownParams["Flags"] = Flags;
                MBOShutdownParams["Reserved"] = "0";

                foreach (ManagementObject manObj in MCWin32.GetInstances())
                {
                    MBOShutdown = manObj.InvokeMethod("Win32Shutdown", MBOShutdownParams, null);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion

Step 7
Shut Down
Double click the btnShutDown button to create a click event handler and call the above function(ShutDownWindows) . Flag "1" indicates ShutDown,it is look like this

private void btnShutDown_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to shutdown your computer?", "Shutdown", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    ShutDownWindows("1"); // Shut down the computer  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

Step 8
Restart
Double click the btnRestart button to create a click event handler and call the above function(ShutDownWindows) . Flag "2" indicates Restart,it is look like this

 

private void btnRestart_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to restart your computer?", "Restart", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    ShutDownWindows("2"); // Restart the computer  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Step 9
Log Off
Double click the btnLogOff button to create a click event handler and call the above function(ShutDownWindows) . Flag "0" indicates Log Off,it is look like this


private void btnLogOff_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to log off your computer?", "Log Off", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    ShutDownWindows("0"); // Log off the computer  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


Full Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
using System.Management;

namespace SolShutdown
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        #region Window API

        [DllImport("user32.dll")]
        public static extern void LockWorkStation();

        #endregion

        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnLock_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to Lock your computer?", "Lock Computer", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    LockWorkStation(); 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

        #region Methods

        /// <summary>
        ///  Shutdown,restart and log off Computer
        /// </summary>
        /// <param name="Flags">Specify the Shut down Parameter
        ///  "1" - Shut down
        ///  "2" - Restart
        ///  "0" - Log off
        /// </param>
        private void ShutDownWindows(String Flags)
        {
            try
            {
                ManagementBaseObject MBOShutdown = null;
                ManagementClass MCWin32 = new ManagementClass("Win32_OperatingSystem");
                MCWin32.Get();

               
                MCWin32.Scope.Options.EnablePrivileges = true;
                ManagementBaseObject MBOShutdownParams = MCWin32.GetMethodParameters("Win32Shutdown");
                
                MBOShutdownParams["Flags"] = Flags;
                MBOShutdownParams["Reserved"] = "0";

                foreach (ManagementObject manObj in MCWin32.GetInstances())
                {
                    MBOShutdown = manObj.InvokeMethod("Win32Shutdown", MBOShutdownParams, null);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion

        private void btnShutDown_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to shutdown your computer?", "Shutdown", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    ShutDownWindows("1"); // Shut down the computer  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

        private void btnRestart_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to restart your computer?", "Restart", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    ShutDownWindows("2"); // Restart the computer  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnLogOff_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to log off your computer?", "Log Off", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    ShutDownWindows("0"); // Log off the computer  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}


Download
Download Source Code

4 comments:

  1. can we detect machine log and sleep in .net?

    ReplyDelete
    Replies
    1. Thank You for sharing your article, This is an interesting & informative blog. It is very useful for the developer like me. Kindly keep blogging. Besides that Wisen has established as Best Corporate Training in Chennai .

      Nowadays JavaScript has tons of job opportunities on various vertical industry. Know more about JavaScript Framework Training visit Corporate Training Companies in India.

      This post gives me detailed information about the technology. corporate training companies in india

      Delete
  2. Use the Following link
    http://codehill.com/2009/01/lock-sleep-or-hibernate-windows-using-c/

    ReplyDelete
  3. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete