C#调用windows api关机(关机api)示例代码分享
using system;
using system.runtime.interopservices;
class shoutdown{
[structlayout(layoutkind.sequential, pack=1)]
internal struct tokpriv1luid
{
public int count;
public long luid;
public int attr;
}
[dllimport("kernel32.dll", exactspelling=true) ]
internal static extern intptr getcurrentprocess();
[dllimport("advapi32.dll", exactspelling=true, setlasterror=true) ]
internal static extern bool openprocesstoken( intptr h, int acc, ref intptr phtok );
[dllimport("advapi32.dll", setlasterror=true) ]
internal static extern bool lookupprivilegevalue( string host, string name, ref long pluid );
[dllimport("advapi32.dll", exactspelling=true, setlasterror=true) ]
internal static extern bool adjusttokenprivileges( intptr htok, bool disall,
ref tokpriv1luid newst, int len, intptr prev, intptr relen );
[dllimport("user32.dll", exactspelling=true, setlasterror=true) ]
internal static extern bool exitwindowsex( int flg, int rea );
internal const int se_privilege_enabled = 0x00000002;
internal const int token_query = 0x00000008;
internal const int token_adjust_privileges = 0x00000020;
internal const string se_shutdown_name = "seshutdownprivilege";
internal const int ewx_logoff = 0x00000000;
internal const int ewx_shutdown = 0x00000001;
internal const int ewx_reboot = 0x00000002;
internal const int ewx_force = 0x00000004;
internal const int ewx_poweroff = 0x00000008;
internal const int ewx_forceifhung = 0x00000010;
private static void doexitwin(int flg)
{
bool ok;
tokpriv1luid tp;
intptr hproc = getcurrentprocess();
intptr htok = intptr.zero;
ok = openprocesstoken( hproc, token_adjust_privileges | token_query, ref htok );
tp.count = 1;
tp.luid = 0;
tp.attr = se_privilege_enabled;
ok = lookupprivilegevalue( null, se_shutdown_name, ref tp.luid );
ok = adjusttokenprivileges( htok, false, ref tp, 0, intptr.zero, intptr.zero );
ok = exitwindowsex( flg, 0 );
}
public static void main()
{
console.writeline("正在关闭计算机……");
// 修改 ewx_shutdown 或者 ewx_logoff, ewx_reboot等实现不同得功能。
// 在xp下可以看到帮助信息,以得到不同得参数
// shutdown /?
doexitwin(ewx_shutdown);
}
}
上一篇: 实现Asp与Asp.Net共享Session的方法
下一篇: 浅谈spring注解之@profile