BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Programming
.NET 1.1+

Exiting Windows and Logging Off Programmatically

If you develop software that updates key Windows configuration settings, you may require that the system be restarted or that the users logs out and performs a new login process. Using Windows API functions, this can be controlled programmatically in C#.

Restarting Windows

If your software has made changes to the configuration of Windows, you may require the operating system to be restarted rather than simply powered down. This is achieved by modifying the ExitWindowsEx flags parameter so that it uses the Reboot flag, rather than the various Shutdown flags. The force flags may also be combined with the Reboot flag.

To add the restart code to the sample application, create a Click event for the restart button as follows:

private void RestartButton_Click(object sender, EventArgs e)
{
    ElevatePrivileges();

    int result = ExitWindowsEx(
        (uint)(ExitFlags.Reboot), (uint)(Reason.SoftwareIssue | Reason.PlannedShutdown));
    if (result == 0) throw new Win32Exception(Marshal.GetLastWin32Error());
}

Logging Off Windows

The last button in the sample application will be used to simply log the user out of Windows. This is useful for minor configuration changes where a full reboot is not necessary. Again, the flags in the ExitWindowsEx function are the only change required.

To complete the sample program, add a Click event for the log off button as follows:

private void LogoffButton_Click(object sender, EventArgs e)
{
    ElevatePrivileges();

    int result = ExitWindowsEx(
        (uint)(ExitFlags.Logoff), (uint)(Reason.ApplicationIssue | Reason.PlannedShutdown));
    if (result == 0) throw new Win32Exception(Marshal.GetLastWin32Error());
}
17 December 2007