C#調(diào)用windows api關(guān)機(jī)(關(guān)機(jī)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("正在關(guān)閉計算機(jī)……");
// 修改 EWX_SHUTDOWN 或者 EWX_LOGOFF, EWX_REBOOT等實現(xiàn)不同得功能。
// 在XP下可以看到幫助信息,以得到不同得參數(shù)
// SHUTDOWN /?
DoExitWin(EWX_SHUTDOWN);
}
}
相關(guān)文章
C# RGB圖像和灰度圖像互轉(zhuǎn)的實現(xiàn)
在我們的圖像類型教程中定義了RGB顏色模型和灰度格式,本文主要介紹了C# RGB圖像和灰度圖像互轉(zhuǎn)的實現(xiàn),文中通過代碼介紹的非常清楚,具有一定的參考價值,感興趣的可以了解一下2023-08-08
C#設(shè)計模式實現(xiàn)之生成器模式和責(zé)任鏈模式
學(xué)完設(shè)計模式之后,你就感覺它會慢慢地影響到你寫代碼的思維方式,下面這篇文章主要給大家介紹了關(guān)于C#設(shè)計模式實現(xiàn)之生成器模式和責(zé)任鏈模式的相關(guān)資料,需要的朋友可以參考下2021-08-08
使用linq to xml修改app.config示例(linq讀取xml)
這篇文章主要介紹了使用linq to xml修改app.config示例,需要的朋友可以參考下2014-02-02
c# 使用特定帳號密碼訪問Windows網(wǎng)路共享
這篇文章主要介紹了c# 使用特定帳號密碼訪問Windows網(wǎng)路共享的方法,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03

