473,469 Members | 1,594 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Shut down Windows from a program.

sashi
1,754 Recognized Expert Top Contributor
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
  2.  
  3. ' Shutdown Flags
  4. Const EWX_LOGOFF = 0
  5. Const EWX_SHUTDOWN = 1
  6. Const EWX_REBOOT = 2
  7. Const EWX_FORCE = 4
  8. Const SE_PRIVILEGE_ENABLED = &H2
  9. Const TokenPrivileges = 3
  10. Const TOKEN_ASSIGN_PRIMARY = &H1
  11. Const TOKEN_DUPLICATE = &H2
  12. Const TOKEN_IMPERSONATE = &H4
  13. Const TOKEN_QUERY = &H8
  14. Const TOKEN_QUERY_SOURCE = &H10
  15. Const TOKEN_ADJUST_PRIVILEGES = &H20
  16. Const TOKEN_ADJUST_GROUPS = &H40
  17. Const TOKEN_ADJUST_DEFAULT = &H80
  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
  35.     Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES
  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
  44.  
  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
  51.  
  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
  108.  
  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
  119.  
  120.  
  121. 'Form code - frmShutdown
  122.  
  123. Private Sub cmdShutdownNow_Click()
  124.     modShutdown.InitiateShutdown GetMachineName, True, False, True, 60, "Message to state reason for shutdown!"
  125. End Sub
  126.  
Dec 4 '06 #1
6 10526
daniel aristidou
491 Contributor
Does this work on all windows Os or xp only ....?
It does not state
Dec 31 '07 #2
kokong
5 New Member
is this reliable to windows vista?
Jan 24 '08 #3
ashasagilnath
1 New Member
avoid more codes and make easier with less codes
Feb 29 '08 #4
babyboy
1 New Member
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
mikimars
1 New Member
plz add the shutdown coding to lern others
Apr 18 '08 #6
raids51
59 New Member
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

2
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...
4
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...
4
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
7
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...
4
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...
5
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...
0
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...
2
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...
5
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...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.