473,224 Members | 1,462 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,224 developers and data experts.

Shut down Windows from a program.

1,754 Expert 1GB
Shut down Windows

For various reasons you may require a shut down of Windows to happen programmatically. For instance if the installation of your program requires system reconfiguration. The following code will do this for you with options to Reboot, etc.

Expand|Select|Wrap|Line Numbers
  1. 'Module code - modShutdown
  3. ' Shutdown Flags
  4. Const EWX_LOGOFF = 0
  5. Const EWX_SHUTDOWN = 1
  6. Const EWX_REBOOT = 2
  7. Const EWX_FORCE = 4
  9. Const TokenPrivileges = 3
  11. Const TOKEN_DUPLICATE = &H2
  13. Const TOKEN_QUERY = &H8
  14. Const TOKEN_QUERY_SOURCE = &H10
  16. Const TOKEN_ADJUST_GROUPS = &H40
  18. Const SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
  19. Const ANYSIZE_ARRAY = 1
  20. Private Type LARGE_INTEGER
  21.     lowpart As Long
  22.     highpart As Long
  23. End Type
  24. Private Type Luid
  25.     lowpart As Long
  26.     highpart As Long
  27. End Type
  28. Private Type LUID_AND_ATTRIBUTES
  29.     'pLuid As Luid
  30.     pLuid As LARGE_INTEGER
  31.     Attributes As Long
  32. End Type
  33. Private Type TOKEN_PRIVILEGES
  34.     PrivilegeCount As Long
  36. End Type
  37. Private Declare Function InitiateSystemShutdown Lib "advapi32.dll" Alias "InitiateSystemShutdownA" (ByVal lpMachineName As String, ByVal lpMessage As String, ByVal dwTimeout As Long, ByVal bForceAppsClosed As Long, ByVal bRebootAfterShutdown As Long) As Long
  38. Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
  39. Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
  40. Private Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, lpLuid As LARGE_INTEGER) As Long
  41. Private Declare Function AdjustTokenPrivileges Lib "advapi32.dll" (ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long
  42. Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
  43. Private Declare Function GetLastError Lib "kernel32" () As Long
  45. Public Function InitiateShutdown(ByVal Machine As String, _
  46.                                  Optional Force As Variant, _
  47.                                  Optional Restart As Variant, _
  48.                                  Optional AllowLocalShutdown As Variant, _
  49.                                  Optional Delay As Variant, _
  50.                                  Optional Message As Variant) As Boolean
  52.     Dim hProc As Long
  53.     Dim OldTokenStuff As TOKEN_PRIVILEGES
  54.     Dim OldTokenStuffLen As Long
  55.     Dim NewTokenStuff As TOKEN_PRIVILEGES
  56.     Dim NewTokenStuffLen As Long
  57.     Dim pSize As Long
  58.     If IsMissing(Force) Then Force = False
  59.     If IsMissing(Restart) Then Restart = True
  60.     If IsMissing(AllowLocalShutdown) Then AllowLocalShutdown = False
  61.     If IsMissing(Delay) Then Delay = 0
  62.     If IsMissing(Message) Then Message = ""
  63.     'Make sure the Machine-name doesn't start with '\\'
  64.     If InStr(Machine, "\\") = 1 Then
  65.         Machine = Right(Machine, Len(Machine) - 2)
  66.     End If
  67.     'check if it's the local machine that's going to be shutdown
  68.     If (LCase(GetMachineName) = LCase(Machine)) Then
  69.         'may we shut this computer down?
  70.         If AllowLocalShutdown = False Then Exit Function
  71.         'open access token
  72.         If OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hProc) = 0 Then
  73.             MsgBox "OpenProcessToken Error: " & GetLastError()
  74.             Exit Function
  75.         End If
  76.         'retrieve the locally unique identifier to represent the Shutdown-privilege name
  77.         If LookupPrivilegeValue(vbNullString, SE_SHUTDOWN_NAME, OldTokenStuff.Privileges(0).pLuid) = 0 Then
  78.             MsgBox "LookupPrivilegeValue Error: " & GetLastError()
  79.             Exit Function
  80.         End If
  81.         NewTokenStuff = OldTokenStuff
  82.         NewTokenStuff.PrivilegeCount = 1
  83.         NewTokenStuff.Privileges(0).Attributes = SE_PRIVILEGE_ENABLED
  84.         NewTokenStuffLen = Len(NewTokenStuff)
  85.         pSize = Len(NewTokenStuff)
  86.         'Enable shutdown-privilege
  87.         If AdjustTokenPrivileges(hProc, False, NewTokenStuff, NewTokenStuffLen, OldTokenStuff, OldTokenStuffLen) = 0 Then
  88.             MsgBox "AdjustTokenPrivileges Error: " & GetLastError()
  89.             Exit Function
  90.         End If
  91.         'initiate the system shutdown
  92.         If InitiateSystemShutdown("\\" & Machine, Message, Delay, Force, Restart) = 0 Then
  93.             Exit Function
  94.         End If
  95.         NewTokenStuff.Privileges(0).Attributes = 0
  96.         'Disable shutdown-privilege
  97.         If AdjustTokenPrivileges(hProc, False, NewTokenStuff, Len(NewTokenStuff), OldTokenStuff, Len(OldTokenStuff)) = 0 Then
  98.             Exit Function
  99.         End If
  100.     Else
  101.         'initiate the system shutdown
  102.         If InitiateSystemShutdown("\\" & Machine, Message, Delay, Force, Restart) = 0 Then
  103.             Exit Function
  104.         End If
  105.     End If
  106.     InitiateShutdown = True
  107. End Function
  109. Function GetMachineName() As String
  110.     Dim sLen As Long
  111.     'create a buffer
  112.     GetMachineName = Space(100)
  113.     sLen = 100
  114.     'retrieve the computer name
  115.     If GetComputerName(GetMachineName, sLen) Then
  116.         GetMachineName = Left(GetMachineName, sLen)
  117.     End If
  118. End Function
  121. 'Form code - frmShutdown
  123. Private Sub cmdShutdownNow_Click()
  124.     modShutdown.InitiateShutdown GetMachineName, True, False, True, 60, "Message to state reason for shutdown!"
  125. End Sub
Dec 4 '06 #1
6 10506
daniel aristidou
491 256MB
Does this work on all windows Os or xp only ....?
It does not state
Dec 31 '07 #2
is this reliable to windows vista?
Jan 24 '08 #3
avoid more codes and make easier with less codes
Feb 29 '08 #4
i want to write a program in VB6.0 for many users so that each usher has a separate password from another user. I want the users to login only three times after which their password will become invalid. I need your help on how to write the code. One textbox will be used for all of them.

I need your help on how to write a VB code that can save the content of a form so that it can be retrieved after shutting down the system or after exitting the VB environment. Please, your help is highly and urgently needed. Thanks
Apr 13 '08 #5
plz add the shutdown coding to lern others
Apr 18 '08 #6
of course you can also just run that one executive in the windows folder that shuts down windows...but i believe it only works on xp and below...or maybe its 2000 and below
Sep 23 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Jesper DK | last post by:
Hi, I would like a program invoked when the computer is shut down or a user logs off. Is there a fix way of doing this. I uses the startup folder to run the program, but I need to run it when...
by: Claire | last post by:
Running XP pro, SP2. Visual studio .NET 2003. App written in C# I have written an application that hides itself when run and shows a notification icon in the system tray. If the main form is...
by: Diogo Alves - Software Developer | last post by:
Hi, I have a application developed by me in C# that does not let windows shut down! What is the problem? is this a Framework bug? I would like to receive some feedback about this issue
by: Mark Rae | last post by:
Hi, I wrote a Windows service for a client a few months ago, and the client has now asked me to modify it so that it shuts itself down under certain circumstances e.g. a catastrophic failure of...
by: pamelafluente | last post by:
Hi Guys, I have a small application which uses a NotifyIcon. The user can set a flag (PreventClosing ) so that when he clicks on the form-cancel button "X", the program will instead be...
by: Jeff S | last post by:
I'm creating a new Windows Forms MDI application... How can I add cause the application to shut itself down after a period of ? I did this in an old COM/VB6 application and I had to have code...
by: ArkJ | last post by:
Hello. I have a little problem. I created a little Service which uses SIP, all works rather well, but when I want to shut it down in the Services panel, it looks as if it's shut down, but in fact...
by: =?Utf-8?B?R2xlbm4=?= | last post by:
i just upgraded from XP to Vista and so far am kicking myself for it. After I installed and got all my drivers updated i went to shut down windows and it will not shut down. It closes all programs...
by: Sheena777 | last post by:
I have a program that I have created and that is permanently running in the back ground on a user's PC. This program is used to check if a finger print scanner is on and if not it will be restarted...
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.