古刹飞鹰 2008-1-16 08:57
写了一个关机程序,无法运行!
[code]import tango.sys.win32.Types;
import tango.sys.win32.UserGdi;
import tango.io.Stdout;
void main()
{
TOKEN_PRIVILEGES tkp;
PHANDLE hToken;
DWORD dw = 0;
OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,hToken);
LPCSTR lpcstr;
LookupPrivilegeValueA(lpcstr, SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid); //获得本地机唯一的标识
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
//AdjustTokenPrivileges(hToken, false, &tkp, dw,&tkp, &dw); //调整获得的权限
uint* tmp;
AdjustTokenPrivileges(hToken, 0, &tkp, 0, &tkp, tmp );
//Stdout("kkk").newline;
ExitWindowsEx(EWX_SHUTDOWN,0); //开始关机
}[/code]就是关不了,,我晕!
yidabu 2008-1-17 08:51
以下内容来自网上,参考代码为C++, 没有试过:
如果是Windows 95/98直接调用ExitWindowsEx()就可以了。
但是现在有麻烦了,NT/2000/XP直接调用ExitWindowsEx()都不行。还要先为调用ExitWindowsEx()的进程获取权限。
以下是MS提供的例子:
#include
BOOL MySystemShutdown()
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
// Get a token for this process.
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return( FALSE );
// 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);
if (GetLastError() != ERROR_SUCCESS) return FALSE;
// Shut down the system and force all applications to close.
if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
SHTDN_REASON_MINOR_UPGRADE |
SHTDN_REASON_FLAG_PLANNED)) return FALSE;
else return TRUE;
}
ExitWindowsEx的第一个参数可以是EWX_LOGOFF,EWX_REBOOT,EWX_FORCE,EWX_POWEROFF,EWX_SHUTDOWN等。
第二个参数是原因代码。
涉及到的API, ExitWindowsEx()在User32.dll中,GetCurrentProcess(),GetLastError() 在Kernel32.dll中,其余在 AdvApi32.dll中。
yidabu 2008-1-17 09:05
你试着加上调试代码就知道问题出在哪里了,ExitWindowsEx并没有执行到:[code]import tango.sys.win32.Types;
import tango.sys.win32.UserGdi;
import tango.io.Stdout;
import tango.util.log.Trace;
void main()
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
// Get a token for this process.
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
Trace.formatln("OpenProcessToken failed");
return -1;
}
// Get the LUID for the shutdown privilege.
LookupPrivilegeValueA(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, cast(PTOKEN_PRIVILEGES)(null), null);
if (GetLastError() != ERROR_SUCCESS)
{
Trace.formatln("AdjustTokeyPrivileges failed");
return -1;
}
// Shut down the system and force all applications to close.
if (!ExitWindowsEx(EWX_SHUTDOWN, 0))
{
Trace.formatln("ExitWindosEx failed");
return -1;
}
else return 0;
}[/code]