Turn off the computer

zhaozj2021-02-11  218

Turn off the computer

Note: Fully translated from MSDN. Very simple. VcBear.

"System Shutdown" is a basic service of the Windows system. There is a "closed system", "logout user", "Lock Workstation" 3 operation. Several functions are available in the SDK to call this service.

The "Close System" function allows your computer to be securely closed. All buffered content in the file system is forced to write to disk. Then, the corresponding dialog is displayed, prompting the user computer to be turned off or ready to be closed. Optionally, the computer is typically restarted after the computer is turned off, not directly cutting off the power. If a process calls the "Logout" function function, all processes within the security environment where the process are terminated, and the current user exits the system. A landp dialog is displayed, looking forward to the login of the new user. The "Lock Workstation" function allows you to protect the computer screen from unauthorized users when leaving your computer. To unlock, you must re-log in with an administrator or an authorized user's account and password.

How to turn off the system: Programs can close local or remote computers in two ways

Turn off the system directly and restart

Windows NT / 2000 and subsequent versions: The program must have SE_SHUTDOWN_NAME privileges to successfully call the shutdown function.

The exitwindowsex function can be used to turn off the system. If the function is successfully called, the system sends a WM_QueryEndSession message for each window, and the program to which the window belongs can be terminated. The program that received this message should respond, clear the environment to release the resource, and then return True to indicate that you can terminate. However, when you call EXITWINDOWEX, if EXW_FORCE is specified, the system is forcibly termination of the relevant process and shuts down, which may result in the loss of data.

This is a program that calls ExitWindowEx shutdown system in NT / 2000 (forced all programs).

Call exitWindowex directly in Windows95 / 98 / ME.

-------------------------------------------------- -------------------------------------------------- ------------

Handle HToken; token_privileges Tkp; // Get a token for this process. If (! Openprocess "

Token_adjust_privileges | token_query, & htokeen))

Error ("OpenProcesstoken");

// Get The Luid for the shutdown privilege. Lookuppprivilerage (NULL, SE_SHUTDOWN_NAME,

& Tkp.privileges [0] .luid);

tkp.PrivilegeCount = 1; // one privilege to set tkp.Privileges [0] .Attributes = SE_PRIVILEGE_ENABLED; // Get the shutdown privilege for this process AdjustTokenPrivileges (hToken, FALSE, & tkp, 0,.

(Ptoken_privileges) null, 0);

// cannot test the return value of adjustTokenPrivileges. If (getLastError ()! = Error_success)

Error ("AdjustTokenPrivileges);

// Shut Down The System and Force All Applications to Close. If (! EXITWINDOWSEX (EWX_SHUTDOWN | EWX_FORCE, 0)) Error ("EXITWINDOWSEX");

-------------------------------------------------- -------------------------------------------------- -------

Windows NT / 2000 and subsequent versions:

The initiatesystemshutdown function can specify a delay. When the delay count is performed, a dialog box is displayed on the target computer that is turned off, prompting the user to log out as soon as possible. Once the count ends, the system immediately is turned off. Prior to this, you can call the AbortSystemShutDown function to stop counting and cancel the corresponding shutdown operation. InitiateSystemShutdown can also specify let the system restart.

InitiateSystemShutdown has a parameter lptstr lpmachinename, which can be specified as a computer name on the network, that is, other computers on the network (if your user has sufficient permissions on the computer).

The following example calls the InitiateSystemShutdown function to turn off the local computer that the user has logged in (to close the remote computer to change the initsystemshutdown first parameter from NULL to the correct computer name or). Similarly, you also need to get SE_SHUTDOWN_NAME permissions.

-------------------------------------------------- -------------------------------------------------- -----

HANDLE hToken; // handle to process token TOKEN_PRIVILEGES tkp; // pointer to token structure BOOL fResult; // system shutdown flag // Get the current process token handle so we can get shutdown // privilege if (OpenProcessToken (GetCurrentProcess (.! ),

Token_adjust_privileges | token_query, & htokeen))

Errorhandler ("OpenProcessToken Failed."); // Get The Luid for Shutdown Privilege. Lookuppprivilerage (NULL, SE_SHUTDOWN_NAME,

& Tkp.privileges [0] .luid);

tkp.PrivilegeCount = 1; // one privilege to set tkp.Privileges [0] .Attributes = SE_PRIVILEGE_ENABLED; // Get shutdown privilege for this process AdjustTokenPrivileges (hToken, FALSE, & tkp, 0,.

(Ptoken_privileges) null, 0);

// cannot test the return value of adjustTokenPrivileges. If (getLastError ()! = Error_success)

ErrorHandler ("AdjustTokenPrivileges Enable Failed."); // Display The Shutdown Dialog Box and Start The Time-Out Countdown. Fresult = InitiateSystemShutdown

Null, // Shut Down Local Computer

Click on the main window and press /

The escape key to cancel shutdown. ", // Message to User

20, // Time-Out Period

False, // ask user to close apps

True); // Reboot After Shutdown

IF (! FRESULT) {

Errorhandler ("INITIATESYSTEMSHUTDOWN FAILED.");

}

// disable shutdown privilege. Tkp.privileges [0] .attributes = 0; AdjustTokenPrivileges (HToken, False, & Tkp, 0, (ptoken_privileges) null, 0); if (getLastError ()! = Error_success) {

Errorhandler ("AdjustTokenPrivileges Disable Faled.");

}

-------------------------------------------------- ---------------

The code to cancel the initialsystemshutdown operation using AbortsystemShutoown is as follows (remember to work before the delay end)

// Get The Current Process Token Handle So We can Get Shutdown // Privilege. If (! OpenProcessToken (GetCurrentProcess (),

Token_adjust_privileges | token_query, & htokeen))

{

Errorhandler ("OpenProcessToken Failed.");

}

// Get The Luid for Shutdown Privilege. Lookuppprivilerage (NULL, SE_SHUTDOWN_NAME,

& Tkp.privileges [0] .luid);

tkp.PrivilegeCount = 1; // one privilege to set tkp.Privileges [0] .Attributes = SE_PRIVILEGE_ENABLED; // Get shutdown privilege for this process AdjustTokenPrivileges (hToken, FALSE, & tkp, 0,.

(Ptoken_privileges) null, 0);

// cannot test the return value of adjustTokenPrivileges. If (getLastError ()! = Error_success)

{

Errorhandler ("AdjustTokenPrivileges Enable Failed.");

}

// prevent the system from shutting down. Fresult = AbortsystemShutdown (null); if (! FRESULT) {

Errorhandler ("AbortsystemShutdown Failed.");

}

// disable shutdown privilege. Tkp.privileges [0] .attributes = 0; AdjustTokenPrivileges (Htoken, False, & TKP, 0,

(Ptoken_privileges) null, 0);

IF (getLastError ()! = error_success

{

Errorhandler ("AdjustTokenPrivileges Disable Faled.");

}

Break;

See MSDN for more information on user rights (privileges)

How to log out that the current user can log off the current user using the exitWindows or ExitWindowSex function.

By default, when the program calls EXITWINDOWS or EXITWINDOWSEX logout, the WM_QueryEndSession message is also sent to each window in the system. The program belongs to this message and returns True indicates that if any one returns false, the logout operation will be canceled.

Windows NT / 2000 and subsequent versions:

When a program responds to WM_QUERYENDSESSION and returns true, it will immediately accept the WM_ENDSESSION message and end immediately, regardless of how other programs respond to WM_QueryEndSession messages.

Windows 95/98 / ME: Only when all programs in the system respond to TRUE for the WM_QueryEndSession message, they will receive a WM_ENDSESSESSION message together and then end.

If you want to force all programs, use the exitWindowSex function, specify the exW_force flag. If this is done, the system does not send a WM_QueryEndSession message, and the procedure that is running directly.

When logging out, the system also sends a CTRL_LOGOFF_EVENT control code to each process. The console program can register a HandlerRoutine routine to process this control code (using the SetConsolectrlHandler function). (More about the control code of the console, see the chapter "Handlerroutine" in MSDN)

In summary: Only all programs are allowed to exit, and the logout operation can be successful. If a program responds to WM_QUERYENDSESSION and returns False, the user cannot be logged out. This will write programs (non-mandatory) that prevents user cancellation or closing.

// This is the code that logs out of the current user

EXITWINDOWS (0, 0);

// Respond to the WM_QueryEndSession message, if NO is selected in the pop-up message box, will be canceled.

Case WM_QUERYENDSESSION: {

Int r;

R = MessageBox (NULL, "Shut Down?", "WM_QueryEndSession", MB_YESNO);

// Return True to Allow Shutdown, False to Stop.

Return R == iDyes;

Break;

}

How to lock the workstation to lock the workstation using the LockWorkStation function. A lock dialog is displayed, telling users that this workstation is being used and has been locked, can be executed to lock the user or administrator unlock, the way to unlock it is to press CTRL_ALT_DEL and log in with the correct account and password. The Condition of the LockWorkStation function successfully called is:

The caller must be a general process running on the system interaction desktop. You must already have a user to log in to the system workstation is not locked. Accept Close Notifications You have a normal window and a message queue to get a closing notification by WM_QueryEndSession or WM_ENDSESSION message.

The console is closed in its control process (Handle Routines). To register a console control process, you should use the setconsolectrlhandler function

The service program accepts the exit notification in its control process. To register a service control process, you should use the RegisterServiceCtrlHandleRex function.

Turn off system function list

Name of the function Function description AbortSystemShutdown cancellation system consists InitSystemShutdown caused closing operation ExitWindows off the current user ExitWindowsEx log off the user, shut down the computer, turn off the computer and restart InitiateSystemShutdown initiate shutdown action, may choose to restart InitiateSystemShutdownEx with InitiateSystemShutdown closed, the extended functions can be System Event Log (Event No. 6006) Write a user-specified dual-band code LockWorkStation lock workstation

System shutdown message WM_ENDSESSION

WPARAM

Indicates whether to terminate the program. If it is true, the instruction is terminated, otherwise false

lparam

Indicates that the user is logged out or the system is turned off. If this parameter contains endsession_logoff (LParam is here a bit-bit value) bit, it is represented by the user.

Windows 2000 and subsequent versions: If lparam == 0, the system is turned off.

The program received this message if wparam is True, after completing the message processing, the program may be turned off at any time. So in the process of this message, you should try to complete the work you need to destroy before the program is destroyed.

WM_QUERYENDSession

WPARAM

Reserved, not used

lparam

With WM_ENDSESSION;

DefWindowProc defaults back: True

转载请注明原文地址:https://www.9cbs.com/read-6059.html

New Post(0)