Модераторы: Snowy, bartram, MetalFan, bems, Poseidon, Riply
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Про shutdown 
:(
    Опции темы
Basя
Дата 10.4.2003, 09:13 (ссылка)    |    (голосов: 0) Загрузка ... Загрузка ... Быстрая цитата Цитата


Unregistered











Я тут обнаружил, что
Код
 wnd := GetWindow(handle, gw_hwndFirst);
 while wnd <> 0 do 
   begin
   wnd := GetWindow(wnd, gw_hwndNext);
   SendMessage(wnd, wm_syscommand, sc_close,0);
   end;

вырубает комп. Правельный ли этот метод?

Это сообщение отредактировал(а) p0s0l - 29.9.2005, 12:32
  Вверх
Vco
Дата 10.4.2003, 17:27 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 311
Регистрация: 13.2.2003
Где: Москва

Репутация: нет
Всего: нет



Незнаю, я только учу дельфи но вот код давно дали. Незнаю, может твой не во всех виндах выключает т.к. мой значительно больше:
Код

function GetWinVersion: String;
var
VersionInfo : TOSVersionInfo;
OSName      : String;
begin
// устанавливаем размер записи
VersionInfo.dwOSVersionInfoSize := SizeOf( TOSVersionInfo );

if Windows.GetVersionEx( VersionInfo ) then
begin
with VersionInfo do
begin
case dwPlatformId of
VER_PLATFORM_WIN32s   : OSName := 'Win32s';
VER_PLATFORM_WIN32_WINDOWS : OSName := 'Windows 95';
VER_PLATFORM_WIN32_NT      : OSName := 'Windows NT';
end; // case dwPlatformId
Result := OSName + ' Version ' + IntToStr( dwMajorVersion ) + '.' + IntToStr( dwMinorVersion ) +
 #13#10' (Build ' + IntToStr( dwBuildNumber ) + ': ' + szCSDVersion + ')';
 end; // with VersionInfo
 end // if GetVersionEx
else
 Result := '';
end;

procedure ShutDown;
const
SE_SHUTDOWN_NAME = 'SeShutdownPrivilege';   // Borland forgot this declaration
var
hToken       : THandle;
tkp          : TTokenPrivileges;
tkpo         : TTokenPrivileges;
zero         : DWORD;
begin
if Pos( 'Windows NT', GetWinVersion) = 1  then // we've got to do a whole buch of things
begin
  zero := 0;
  if not OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then
  begin
  MessageBox( 0, 'Exit Error', 'OpenProcessToken() Failed', MB_OK );
  Exit;
  end; // if not OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken)
  if not OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then
  begin
  MessageBox( 0, 'Exit Error', 'OpenProcessToken() Failed', MB_OK );
  Exit;
end; // if not OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken)


  // SE_SHUTDOWN_NAME
if not LookupPrivilegeValue( nil, 'SeShutdownPrivilege' , tkp.Privileges[ 0 ].Luid ) then
 begin
  MessageBox( 0, 'Exit Error', 'LookupPrivilegeValue() Failed', MB_OK );
  Exit;
 end; // if not LookupPrivilegeValue( nil, 'SeShutdownPrivilege' , tkp.Privileges[0].Luid )
  tkp.PrivilegeCount := 1;
  tkp.Privileges[ 0 ].Attributes := SE_PRIVILEGE_ENABLED;

 AdjustTokenPrivileges( hToken, False, tkp, SizeOf( TTokenPrivileges ), tkpo, zero );
   if Boolean( GetLastError() ) then
    begin
    MessageBox( 0, 'Exit Error', 'AdjustTokenPrivileges() Failed', MB_OK );
    Exit;
 end // if Boolean( GetLastError() )
  else
  ExitWindowsEx( EWX_FORCE or EWX_SHUTDOWN, 0 );
 end // if OSVersion = 'Windows NT'
 else
 begin // just shut the machine down
 ExitWindowsEx( EWX_FORCE or EWX_SHUTDOWN, 0 );
   end; // else
end;



--------------------
Я всегда где-то рядом...! user posted image
PM MAIL WWW ICQ   Вверх
Vco
Дата 10.4.2003, 17:28 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 311
Регистрация: 13.2.2003
Где: Москва

Репутация: нет
Всего: нет



А, ну в моём коде :
function GetWinVersion: String; функция. Значит + определение виндовса


--------------------
Я всегда где-то рядом...! user posted image
PM MAIL WWW ICQ   Вверх
XpyDi
Дата 10.4.2003, 17:40 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 114
Регистрация: 25.11.2002
Где: USSR

Репутация: нет
Всего: 2



Ну что могу сказать я использовал и использую финкцию очень похожую на приведённую Vco, а метод который привел Basя будет работать только на Win9x, в NT нужно иметь определенные привелегии, чтобы выключить компьютер. К тому же насколько я понял у Basя, просто вырубаеться какое-то окно , которое при своём закрытии просто производит выключение компьютера(какое окноо не знаю, на 9x уже 3 года не работал).
PM MAIL WWW ICQ   Вверх
Basя
Дата 10.4.2003, 18:02 (ссылка)    |    (голосов: 0) Загрузка ... Загрузка ... Быстрая цитата Цитата


Unregistered











Цитата

Ну что могу сказать я использовал и использую финкцию очень похожую на приведённую Vco, а метод который привел Basя будет работать только на Win9x, в NT нужно иметь определенные привелегии, чтобы выключить компьютер. К тому же насколько я понял у Basя, просто вырубаеться какое-то окно , которое при своём закрытии просто производит выключение компьютера(какое окноо не знаю, на 9x уже 3 года не работал).


Я это использовал в XP! smile.gif)))))))
  Вверх
Pakshin A. S.
Дата 11.4.2003, 08:28 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник Клуба
Сообщений: 5056
Регистрация: 16.2.2003

Репутация: нет
Всего: 61



Ну насчёт привелегий:
В NT подобных штуках есть функция AdjustTokenPrivleges().
Вот Help из Delphi:
Цитата

The AdjustTokenPrivileges function enables or disables privileges in the specified access token. Enabling or disabling privileges in an access token requires TOKEN_ADJUST_PRIVILEGES access.

BOOL AdjustTokenPrivileges(

    HANDLE TokenHandle, // handle to token that contains privileges
    BOOL DisableAllPrivileges, // flag for disabling all privileges
    PTOKEN_PRIVILEGES NewState, // pointer to new privilege information
    DWORD BufferLength, // size, in bytes, of the PreviousState buffer
    PTOKEN_PRIVILEGES PreviousState, // receives original state of changed privileges
    PDWORD ReturnLength  // receives required size of the PreviousState buffer
  );


Parameters

TokenHandle

Identifies the access token that contains the privileges to be modified.

DisableAllPrivileges

Specifies whether the function disables all of the token's privileges. If this value is TRUE, the function disables all privileges and ignores the NewState parameter. If it is FALSE, the function modifies privileges based on the information pointed to by the NewState parameter.

NewState

Pointer to a TOKEN_PRIVILEGES structure that specifies an array of privileges and their attributes. If the DisableAllPrivileges parameter is FALSE, AdjustTokenPrivileges enables or disables these privileges for the token. If you set the SE_PRIVILEGE_ENABLED attribute for a privilege, the function enables that privilege; otherwise, it disables the privilege.
If DisableAllPrivileges is TRUE, the function ignores this parameter.

BufferLength

Specifies the size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be NULL if the PreviousState parameter is NULL.

PreviousState

Pointer to a buffer that the function fills with a TOKEN_PRIVILEGES structure containing the previous state of any privileges the function modifies. The token must be open for TOKEN_QUERY access to use this parameter. This parameter can be NULL.
If you specify a buffer that is too small to receive the complete list of modified privileges, the function fails and does not adjust any privileges. In this case, the function sets the variable pointed to by the ReturnLength parameter to the number of bytes required to hold the complete list of modified privileges.

ReturnLength

Pointer to a variable that receives the required size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be NULL if PreviousState is NULL.



Return Values

If the function succeeds, the return value is nonzero. To determine whether the function adjusted all of the specified privileges, call GetLastError, which returns one of the following values when the function succeeds:

Value Description
ERROR_SUCCESS The function adjusted all specified privileges.
ERROR_NOT_ALL_ASSIGNED The token does not have one or more of the privileges specified in the NewState parameter. The function may succeed with this error value even if no privileges were adjusted. The PreviousState parameter indicates the privileges that were adjusted.


If the function fails, the return value is zero. To get extended error information, call GetLastError
.

Remarks

The AdjustTokenPrivileges function cannot add new privileges to the access token. It can only enable or disable the token's existing privileges. To determine the token's privileges, call the GetTokenInformation function.
Note that the NewState parameter can specify privileges that the token does not have, without causing the function to fail. In this case, the function adjusts the privileges that the token does have, ignores the other privileges, and returns success. Call the GetLastError function to determine whether the function adjusted all of the specified privileges. The PreviousState parameter indicates the privileges that were adjusted.

The PreviousState parameter retrieves a TOKEN_PRIVILEGES structure containing the the original state of the adjusted privileges. To restore the original state, pass the PreviousState pointer as the NewState parameter in a subsequent call to the AdjustTokenPrivileges function

С её помощью можно получить привилегию на закрытие Windowsa SE_SHUTDOWN_NAME.
PM   Вверх
XpyDi
Дата 11.4.2003, 17:27 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 114
Регистрация: 25.11.2002
Где: USSR

Репутация: нет
Всего: 2



2Basя:
Тогда пару таких вопросов:
1 Сие чудо ты запускаешь от имени админа?
2 У тебя есть кусок:
wnd := GetWindow(handle, gw_hwndFirst);
Откуда handle береться(т.е. что находиться выше этой строки).?

2Pakshin A. S.:
У чему это ты? Вроде бы никто не спрашивал про AdjustTokenPrivleges, да и если заговорил про привелегии, то не забывай про OpenProcessToken и многие другие. Да и в описание если приводишь по собственной инициативе, то приводи не из Delphi'овского Help'а(который есть практически у всех), а из MSDN или где еще полнее освещена тема или на русском.
PM MAIL WWW ICQ   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Delphi: WinAPI и системное программирование"
Snowybartram
MetalFanbems
PoseidonRrader
Riply

Запрещено:

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Литературу по Delphi обсуждаем здесь
  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы по реализации алгоритмов рассматриваются здесь
  • 90% ответов на свои вопросы можно найти в DRKB (Delphi Russian Knowledge Base) - крупнейшем в рунете сборнике материалов по Дельфи
  • 99% ответов по WinAPI можно найти в MSDN Library, оставшиеся 1% здесь

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Snowy, bartram, MetalFan, bems, Poseidon, Rrader, Riply.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Delphi: WinAPI и системное программирование | Следующая тема »


 




[ Время генерации скрипта: 0.0485 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.