1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
   |  
        [DllImport("user32.dll")]
        internal static extern bool ExitWindowsEx(uint flags, uint reason);
 
        [DllImport("user32.dll")]
        internal static extern void LockWorkStation();
 
        // from Win32 header file: reason.h
        const uint SHTDN_REASON_MAJOR_APPLICATION = 0x00040000;
        const uint SHTDN_REASON_MINOR_INSTALLATION = 0x00000002;
        const uint SHTDN_REASON_FLAG_PLANNED = 0x80000000;
 
        // from Win32 header file: winuser.h
        const int SE_PRIVILEGE_ENABLED = 0x00000002;
        const int TOKEN_QUERY = 0x00000008;
        const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
        const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
        const int EWX_LOGOFF = 0x00000000;
        const int EWX_SHUTDOWN = 0x00000001;
        const int EWX_REBOOT = 0x00000002;
        const int EWX_FORCE = 0x00000004;
        const int EWX_POWEROFF = 0x00000008;
        const int EWX_FORCEIFHUNG = 0x00000010; 
 
        // redémarre le PC
        public static void restart() {
            adjusteShutDownPrivileges();
            ExitWindowsEx(EWX_REBOOT, SHTDN_REASON_MAJOR_APPLICATION);
        }
 
        // éteind le PC
        public static void shutdown() {
            adjusteShutDownPrivileges();
            ExitWindowsEx(EWX_SHUTDOWN, SHTDN_REASON_MAJOR_APPLICATION);
        }
 
        // Set shutdown privileges for this application
        private static void adjusteShutDownPrivileges(){
            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);
        } | 
Partager