Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C++ Builder > Отключение компьютера


Автор: Slayers 17.7.2005, 02:04
Есть ф-ция ExitWindowsEx() но как она работает не могу понять.

А мне просто нужно перезагружать/выключить камп! smile

Автор: Zzz 17.7.2005, 02:17
А что не понятно? Посмотри MSDN, там вроде все написано...
Вот:
Цитата

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,       // shutdown operation
  DWORD dwReserved   // reserved
);

Parameters
uFlags
Specifies the type of shutdown. This parameter must include one of the following values: Value Meaning
EWX_LOGOFF Shuts down all processes running in the security context of the process that called the ExitWindowsEx function. Then it logs the user off.
EWX_POWEROFF Shuts down the system and turns off the power. The system must support the power-off feature.
Windows NT: The calling process must have the SE_SHUTDOWN_NAME privilege. For more information, see the following Remarks section.

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

EWX_SHUTDOWN 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.
Windows NT: The calling process must have the SE_SHUTDOWN_NAME privilege. For more information, see the following Remarks section.



This parameter can optionally include the following values: Value Meaning
EWX_FORCE 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.
EWX_FORCEIFHUNG Windows NT 5.0 and later: Forces processes to terminate if they do not respond to the WM_QUERYENDSESSION or WM_ENDSESSION message. This flag is ignored if EWX_FORCE is used.



dwReserved
Reserved; this parameter is ignored.
Return Values
If the function succeeds, the return value is nonzero.

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




Вот напрмер при нажатии на кнопку - разлогинится...

Код

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  ExitWindowsEx(EWX_LOGOFF,0);
}

Автор: Slayers 17.7.2005, 02:32
to -> szz "LOGOFF у меня работает остальное НЕТ"
Я пишу
Код

bool b = ExitWindowsEx(EWX_REBOOT, 0);
if(!b)
 MessageBox(Handle, "Unable to shootDown system!!!!!!");// и т.д.
else 
       Close();


Пишет "Unable to shootDown system!!!!!!" и всё.
Либо просто выходит с програмы!
smile НОРМАЛЬНЫЙ!

Автор: codelord 17.7.2005, 15:04
Slayers Если интересует, покопаюсь. Реализация коммандной строки, наподобии меню выполнить.
т.е там можно просто будет указать строку, например shutdown -r -t 00

Автор: Mayk 17.7.2005, 15:08
Нужно еще привелегии иметь. Я делал вот так.
Код

    flags = EWX_POWEROFF;

    /*taken from OWL examples(OWL/apps/applaunc)*/
    HANDLE            hToken;
    LUID              takeOwnershipValue;
    TOKEN_PRIVILEGES  tkp;

    if (!OpenProcessToken(GetCurrentProcess(),
                          TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
      return ERR_UNABLE_TO_DO;
    if (!LookupPrivilegeValue(0, SE_SHUTDOWN_NAME, &takeOwnershipValue))
      return ERR_UNABLE_TO_DO;

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = takeOwnershipValue;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    AdjustTokenPrivileges(hToken, false, &tkp, sizeof(TOKEN_PRIVILEGES), 0, 0);
    if (GetLastError())
      return ERR_UNABLE_TO_DO;
        if(ExitWindowsEx(flags,0))
        return ERR_OK;
   return ERR_UNABLE_TO_DO;

Автор: codelord 17.7.2005, 15:32
ладно я не стал дожидаться,
будем надеяться тебе подойдет.
Код

void __fastcall TForm1::Button1Click(TObject *Sender)
{
        TStartupInfo si;
        TProcessInformation pi;
        AnsiString cmdline;
        ZeroMemory(&si,sizeof(si)); si.cb = sizeof(si);
        cmdline ="shutdown -r -t 30"; //комманда время сам поставишь
        if (!CreateProcess( NULL, // No module name (use command line).
        cmdline.c_str(), // Command line.
        NULL, // Process handle not inheritable.
        NULL, // Thread handle not inheritable.
        false, // Set handle inheritance to FALSE.
        0, // No creation flags.
        NULL, // Use parent's environment block.
        NULL, // Use parent's starting directory.
        &si, // Pointer to STARTUPINFO structure.
        &pi )) // Pointer to PROCESS_INFORMATION structure.
        { ; }
}


на всякий случай:

Использование: shutdown [-i | -l | -s | -r | -a] [-f] [-m \\<компьютер>]
[-t xx] [-c "комментарий"] [-d up:xx:yy]

Без аргументов Вывод справки по использованию (как и -?)
-i Отображение интерфейса, д.быть первым параметром
-l Выход (не совместим с параметром -m)
-s Завершение работы компьютера
-r Перезагрузка компьютера
-a Прекращение завершения работы системы
-m \\<компьютер> Удаленный компьютер, на котором выполняется
действие
-t xx Таймаут завершения работы - xx сек.
-c "comment" Комментарий (не более 127 знаков)
-f Принудительное завершение приложений без
предварительного предупреждения
-d [u][p]:xx:yy Код причины завершения работы
u - пользовательский код
p - код запланированного завершения
xx - основной код причины (1 - 255)
yy - дополнительный код причины (1 - 65535)

Автор: Slayers 18.7.2005, 01:40
smile codelord большое Вам спасибо всё отлично работает!


код от Mayk _а не пошол smile но и за это спасибо.

Автор: codelord 18.7.2005, 10:42
Пример от Mayk Лучше подходит для прегрузки, для этого надо превратить его в функцию: вот так я сделал и у меня пошло.
Код

#define ERR_UNABLE_TO_DO 0   // я так понимаю это пофиг как
#define ERR_OK 1
DWORD myreboot()
        {

            /*taken from OWL examples(OWL/apps/applaunc)*/
HANDLE            hToken;
LUID              takeOwnershipValue;
TOKEN_PRIVILEGES  tkp;
if (!OpenProcessToken(GetCurrentProcess(),
                          TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
           return ERR_UNABLE_TO_DO;
    if (!LookupPrivilegeValue(0, SE_SHUTDOWN_NAME, &takeOwnershipValue))
      return ERR_UNABLE_TO_DO;
    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = takeOwnershipValue;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    AdjustTokenPrivileges(hToken, false, &tkp, sizeof(TOKEN_PRIVILEGES), 0, 0);
    if (GetLastError())
      return ERR_UNABLE_TO_DO;
        if(ExitWindowsEx(EWX_REBOOT,0))
        return ERR_OK;
        return ERR_UNABLE_TO_DO;
        }


для презагрузки достаточно вызвать функцию myreboot();

Автор: Slayers 19.7.2005, 02:33
И то правда так намного лучше работать. Спасиба smile

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)