Помощь - Поиск - Пользователи - Календарь
Полная версия: Перезагрузка компьютера на Delphi
Форум «Всё о Паскале» > Delphi, Assembler и другие языки. > Delphi
#$# PaVeL #$#
mega_chok.gif[SIZE=14] Может кто подскажет: "Как перезагрузить комп програмно, из Delphi в OS Windows XP".А то уж совсем сума сошёл. wacko.gif
P.S.: Предпочтительно готовый участок кода! cool.gif
Fang
Вот так наверное:

Код
ExitWindowsEx(EWX_REBOOT,0);
#$# PaVeL #$#
Чтобы перезагрузить Windows XP НАДО ПРИВИЛЕГИИ АДМИНИСТРАТОРА ПОЛУЧИТЬ! А я незнаю как! mad.gif
Ozzя
Цитата(#$# PaVeL #$# @ 25.11.2005 14:15)
Чтобы перезагрузить Windows XP НАДО ПРИВИЛЕГИИ АДМИНИСТРАТОРА ПОЛУЧИТЬ! А я незнаю как! mad.gif

Изменение привелегий 
{
For some functions you need to get the right privileges
on a Windows NT machine.
(e.g: To shut down or restart windows with ExitWindowsEx or
to change the system time)
The following code provides a procedure to adjust the privileges.
The AdjustTokenPrivileges() function enables or disables privileges
in the specified access token.
}

// NT Defined Privileges from winnt.h

const
SE_CREATE_TOKEN_NAME = 'SeCreateTokenPrivilege';
SE_ASSIGNPRIMARYTOKEN_NAME = 'SeAssignPrimaryTokenPrivilege';
SE_LOCK_MEMORY_NAME = 'SeLockMemoryPrivilege';
SE_INCREASE_QUOTA_NAME = 'SeIncreaseQuotaPrivilege';
SE_UNSOLICITED_INPUT_NAME = 'SeUnsolicitedInputPrivilege';
SE_MACHINE_ACCOUNT_NAME = 'SeMachineAccountPrivilege';
SE_TCB_NAME = 'SeTcbPrivilege';
SE_SECURITY_NAME = 'SeSecurityPrivilege';
SE_TAKE_OWNERSHIP_NAME = 'SeTakeOwnershipPrivilege';
SE_LOAD_DRIVER_NAME = 'SeLoadDriverPrivilege';
SE_SYSTEM_PROFILE_NAME = 'SeSystemProfilePrivilege';
SE_SYSTEMTIME_NAME = 'SeSystemtimePrivilege';
SE_PROF_SINGLE_PROCESS_NAME = 'SeProfileSingleProcessPrivilege';
SE_INC_BASE_PRIORITY_NAME = 'SeIncreaseBasePriorityPrivilege';
SE_CREATE_PAGEFILE_NAME = 'SeCreatePagefilePrivilege';
SE_CREATE_PERMANENT_NAME = 'SeCreatePermanentPrivilege';
SE_BACKUP_NAME = 'SeBackupPrivilege';
SE_RESTORE_NAME = 'SeRestorePrivilege';
SE_SHUTDOWN_NAME = 'SeShutdownPrivilege';
SE_DEBUG_NAME = 'SeDebugPrivilege';
SE_AUDIT_NAME = 'SeAuditPrivilege';
SE_SYSTEM_ENVIRONMENT_NAME = 'SeSystemEnvironmentPrivilege';
SE_CHANGE_NOTIFY_NAME = 'SeChangeNotifyPrivilege';
SE_REMOTE_SHUTDOWN_NAME = 'SeRemoteShutdownPrivilege';
SE_UNDOCK_NAME = 'SeUndockPrivilege';
SE_SYNC_AGENT_NAME = 'SeSyncAgentPrivilege';
SE_ENABLE_DELEGATION_NAME = 'SeEnableDelegationPrivilege';
SE_MANAGE_VOLUME_NAME = 'SeManageVolumePrivilege';

// Enables or disables privileges debending on the bEnabled
// Aktiviert oder deaktiviert Privilegien, abhangig von bEnabled

function NTSetPrivilege(sPrivilege: string; bEnabled: Boolean): Boolean;
var
hToken: THandle;
TokenPriv: TOKEN_PRIVILEGES;
PrevTokenPriv: TOKEN_PRIVILEGES;
ReturnLength: Cardinal;
begin
Result := True;
// Only for Windows NT/2000/XP and later.
if not (Win32Platform = VER_PLATFORM_WIN32_NT) then Exit;
Result := False;

// obtain the processes token
if OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then
begin
try
// Get the locally unique identifier (LUID) .
if LookupPrivilegeValue(nil, PChar(sPrivilege),
TokenPriv.Privileges[0].Luid) then
begin
TokenPriv.PrivilegeCount := 1; // one privilege to set

case bEnabled of
True: TokenPriv.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
False: TokenPriv.Privileges[0].Attributes := 0;
end;

ReturnLength := 0; // replaces a var parameter
PrevTokenPriv := TokenPriv;

// enable or disable the privilege

AdjustTokenPrivileges(hToken, False, TokenPriv, SizeOf(PrevTokenPriv),
PrevTokenPriv, ReturnLength);
end;
finally
CloseHandle(hToken);
end;
end;
// test the return value of AdjustTokenPrivileges.
Result := GetLastError = ERROR_SUCCESS;
if not Result then
raise Exception.Create(SysErrorMessage(GetLastError));
end;
Взято с сайта http://www.swissdelphicenter.ch/en/tipsindex.php
#$# PaVeL #$#
Ну с привелегиями вроде понял только какую использовать для перезагрузки?
FreeMan
Вроде SeShutdownPrivilege

Тут то, что нужно
#$# PaVeL #$#
Не получается!!!! nea.gif
SeShutdownPrivilege - Не получается! Что делать?
Может что не правильно делаю!??
volvo
Ну, так покажи, КАК ты делаешь? Телепатов у нас нет... А ты пока ни одной строчки своего кода не показал...
#$# PaVeL #$#
Чё правда не телепаты????????????????????????? blum.gif
А, я думал........... nea.gif
Ну да ладно Вот :
const
SE_CREATE_TOKEN_NAME = 'SeCreateTokenPrivilege';
SE_ASSIGNPRIMARYTOKEN_NAME = 'SeAssignPrimaryTokenPrivilege';
SE_LOCK_MEMORY_NAME = 'SeLockMemoryPrivilege';
SE_INCREASE_QUOTA_NAME = 'SeIncreaseQuotaPrivilege';
SE_UNSOLICITED_INPUT_NAME = 'SeUnsolicitedInputPrivilege';
SE_MACHINE_ACCOUNT_NAME = 'SeMachineAccountPrivilege';
SE_TCB_NAME = 'SeTcbPrivilege';
SE_SECURITY_NAME = 'SeSecurityPrivilege';
SE_TAKE_OWNERSHIP_NAME = 'SeTakeOwnershipPrivilege';
SE_LOAD_DRIVER_NAME = 'SeLoadDriverPrivilege';
SE_SYSTEM_PROFILE_NAME = 'SeSystemProfilePrivilege';
SE_SYSTEMTIME_NAME = 'SeSystemtimePrivilege';
SE_PROF_SINGLE_PROCESS_NAME = 'SeProfileSingleProcessPrivilege';
SE_INC_BASE_PRIORITY_NAME = 'SeIncreaseBasePriorityPrivilege';
SE_CREATE_PAGEFILE_NAME = 'SeCreatePagefilePrivilege';
SE_CREATE_PERMANENT_NAME = 'SeCreatePermanentPrivilege';
SE_BACKUP_NAME = 'SeBackupPrivilege';
SE_RESTORE_NAME = 'SeRestorePrivilege';
SE_SHUTDOWN_NAME = 'SeShutdownPrivilege';
SE_DEBUG_NAME = 'SeDebugPrivilege';
SE_AUDIT_NAME = 'SeAuditPrivilege';
SE_SYSTEM_ENVIRONMENT_NAME = 'SeSystemEnvironmentPrivilege';
SE_CHANGE_NOTIFY_NAME = 'SeChangeNotifyPrivilege';
SE_REMOTE_SHUTDOWN_NAME = 'SeRemoteShutdownPrivilege';
SE_UNDOCK_NAME = 'SeUndockPrivilege';
SE_SYNC_AGENT_NAME = 'SeSyncAgentPrivilege';
SE_ENABLE_DELEGATION_NAME = 'SeEnableDelegationPrivilege';
SE_MANAGE_VOLUME_NAME = 'SeManageVolumePrivilege';

// Enables or disables privileges debending on the bEnabled
// Aktiviert oder deaktiviert Privilegien, abhangig von bEnabled

function NTSetPrivilege(sPrivilege: string; bEnabled: Boolean): Boolean;
var
hToken: THandle;
TokenPriv: TOKEN_PRIVILEGES;
PrevTokenPriv: TOKEN_PRIVILEGES;
ReturnLength: Cardinal;
begin
Result := True;
// Only for Windows NT/2000/XP and later.
if not (Win32Platform = VER_PLATFORM_WIN32_NT) then Exit;
Result := False;

// obtain the processes token
if OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then
begin
try
// Get the locally unique identifier (LUID) .
if LookupPrivilegeValue(nil, PChar(sPrivilege),
TokenPriv.Privileges[0].Luid) then
begin
TokenPriv.PrivilegeCount := 1; // one privilege to set

case bEnabled of
True: TokenPriv.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
False: TokenPriv.Privileges[0].Attributes := 0;
end;

ReturnLength := 0; // replaces a var parameter
PrevTokenPriv := TokenPriv;

// enable or disable the privilege

AdjustTokenPrivileges(hToken, False, TokenPriv, SizeOf(PrevTokenPriv),
PrevTokenPriv, ReturnLength);
end;
finally
CloseHandle(hToken);
end;
end;
// test the return value of AdjustTokenPrivileges.
Result := GetLastError = ERROR_SUCCESS;
if not Result then
raise Exception.Create(SysErrorMessage(GetLastError));
end;



begin
NTSetPrivilege(SE_SHUTDOWN_NAME,True);
ExitWindowsEx(EW_RESTARTWINDOWS,0);
End;

Ну вот собственно. blink.gif
volvo
#$# PaVeL #$#,
попробуй
ExitWindowsEx(EWX_REBOOT+EWX_FORCE, 0);
#$# PaVeL #$#
Ну, понятно только перед тем как закрыть тему хотелось бы узнать зачем плюсуется EWX_FORCE.
И, я, всем благодарен за оказанную мне помощь! good.gif
GoodWind
если не изменяет склероз, включает режим "форсированной" перезагрузки.
кстати, буду благодарен, если протестируешь форсированный и нефорсированный режимы и скажешь результаты (время ушедшее на перезагрузку).
#$# PaVeL #$#
Чё то я незаметил разницы комп выключается очень быстро и без того!
Слишком он быстрый! smile.gif

Вот и всё! smile.gif blink.gif
Есть тупой вопрос как закрыть тему?!?

есть вопрос еще тупее: зачем закрывать ?!
GoodWind
а в чем тогда его смысл blink.gif
кто знает ?
volvo
Цитата(DRKB)
Замечу также что флаг EWX_FORCE необходим только для принудительного завершения при выдаче каких либо сообщений или модальных окон, что воспрепятствует завершению, например, "К компьютеру подключены пользователи. Данные могут быть утярены. Вы хотите завершить работу?"
GoodWind
Цитата
ExitWindowsEx
The ExitWindowsEx function either logs off the current user, shuts down the system, or shuts down and restarts the system. It sends the WM_QUERYENDSESSION message to all applications to determine if they can be terminated.

BOOL ExitWindowsEx(
UINT uFlags,
DWORD dwReason
);
Parameters
uFlags [in] Shutdown type. This parameter must include one of the following values. Value Meaning EWX_LOGOFF
0 Shuts down all processes running in the logon session of the process that called the ExitWindowsEx function. Then it logs the user off.This flag can be used only by processes running in an interactive user's logon session.

EWX_POWEROFF
0x00000008 Shuts down the system and turns off the power. The system must support the power-off feature. The calling process must have the SE_SHUTDOWN_NAME privilege. For more information, see the following Remarks section.

EWX_REBOOT
0x00000002 Shuts down the system and then restarts the system. The calling process must have the SE_SHUTDOWN_NAME privilege. For more information, see the following Remarks section.

EWX_SHUTDOWN
0x00000001 Shuts down the system to a point at which it is safe to turn off the power. All file buffers have been flushed to disk, and all running processes have stopped. The calling process must have the SE_SHUTDOWN_NAME privilege. For more information, see the following Remarks section.

Specifying this flag will not turn off the power even if the system supports the power-off feature. You must specify EWX_POWEROFF to do this.

Windows XP SP1: If the system supports the power-off feature, specifying this flag turns off the power.


This parameter can optionally include one of the following values.

Value Meaning EWX_FORCE
0x00000004
Windows 2000/NT: Forces processes to terminate. When this flag is set, the system does not send the WM_QUERYENDSESSION and WM_ENDSESSION messages. This can cause the applications to lose data. Therefore, you should only use this flag in an emergency.Starting with Windows XP, these messages will always be sent.

EWX_FORCEIFHUNG
0x00000010 Forces processes to terminate if they do not respond to the WM_QUERYENDSESSION or WM_ENDSESSION message within the timeout interval. For more information, see the Remarks.
Windows NT and Windows Me/98/95: This value is not supported.

информация с www.msdn.com
#$# PaVeL #$#
Спасибо материал интересный. good.gif
Только, если честно, не люблю английский! smile.gif mad.gif smile.gif mad.gif
Это текстовая версия — только основной контент. Для просмотра полной версии этой страницы, пожалуйста, нажмите сюда.