关于ExitWindows()一个很郁闷的问题!
本人的操作系统是XP,编译环境是VC++6.0以下是我的代码:
DWORD WINAPI CMyDlg::TimerThread()
{
DWORD m_WaitResult;
while (true)
{
m_WaitResult = WaitForSingleObject(m_hReset, 1000);
if (WAIT_OBJECT_0 == m_WaitResult)
{
SetDlgItemInt(IDC_HOUR, m_Hour);
SetDlgItemInt(IDC_MINUTE, m_Minute);
SetDlgItemInt(IDC_SECOND, m_Second);
}
else{
if (0 == m_Second)
{
if (0 == m_Minute)
{
if (0 == m_Hour)
{
::ExitWindowsEx(EWX_POWEROFF|EWX_FORCE , 0);
return 0;
}
else{
--m_Hour;
m_Minute = 59;
m_Second = 59;
SetDlgItemInt(IDC_SECOND, m_Second);
SetDlgItemInt(IDC_MINUTE, m_Minute);
SetDlgItemInt(IDC_HOUR, m_Hour);
}
}
else{
--m_Minute;
m_Second = 59;
SetDlgItemInt(IDC_SECOND, m_Second);
SetDlgItemInt(IDC_MINUTE, m_Minute);
}
}
else --m_Second;
SetDlgItemInt(IDC_SECOND, m_Second);
}
}
}
以上是我用来定时关机的代码;编译能通过,逻辑没有错误,当我点VC6中的执行图标时,程序能够正常执行,并能成功疳准时关机,可是当我退出VC++程序,点Debug中的.exe文件时,程序也能运行,只是时间到了不会关机!经过我的反复测试发现,::ExitWindowsEx(EWX_POWEROFF|EWX_FORCE , 0)函数只有在VC6中点执行图标时才起作用,点debug中的exe图标时,程序运行就不起作用了,请问是为什么呢?应该怎么解决,我将编译器换成release版结果也是一样
等待中......
[解决办法]
需要先取得SE_SHUTDOWN_NAME权限才能正确运行
- C/C++ code
HANDLE hToken; TOKEN_PRIVILEGES tkp; // Get a token for this process. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) Error("OpenProcessToken"); // Get the LUID for the shutdown privilege. LookupPrivilegeValue(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"); 