首页 > 其他分享 >CSharp闪电关机/重启类

CSharp闪电关机/重启类

时间:2022-11-01 14:33:25浏览次数:67  
标签:关机 IntPtr 闪电 private dll ZwShutdownSystem RtlAdjustPrivilege CSharp hLib

调用ntdll.dll内的 ZwShutdownSystem 函数实现闪电关机/重启的功能

using System;
using System.Runtime.InteropServices;

namespace Biltong_SystemPower
{
    public enum Options
    {
        Poweroff = 2,
        Reboot=1
    }
    public class SystemPower
    {
        private delegate uint ZwShutdownSystem(int ShutdownAction);
        private delegate uint RtlAdjustPrivilege(int Privilege, bool Enable, bool CurrentThread, ref int Enabled);

        [DllImport("kernel32.dll")]
        private static extern IntPtr LoadLibrary(string path);
        [DllImport("kernel32.dll")]
        private static extern IntPtr GetProcAddress(IntPtr lib, string funcName);
        [DllImport("kernel32.dll")]
        private static extern bool FreeLibrary(IntPtr lib);

        //将要执行的函数转换为委托
        private Delegate Invoke(string APIName, Type t, IntPtr hLib)
        {
            IntPtr api = GetProcAddress(hLib, APIName);
            return (Delegate)Marshal.GetDelegateForFunctionPointer(api, t);
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread()]
        public void Setup(Int32 Options)
        {
            IntPtr hLib = LoadLibrary("ntdll.dll");
            RtlAdjustPrivilege rtla = (RtlAdjustPrivilege)Invoke("RtlAdjustPrivilege", typeof(RtlAdjustPrivilege), hLib);
            ZwShutdownSystem shutdown = (ZwShutdownSystem)Invoke("ZwShutdownSystem", typeof(ZwShutdownSystem), hLib);

            int en = 0;
            uint ret = rtla(0x13, true, false, ref en);
            //SE_SHUTDOWN_PRIVILEGE = 0x13;     //关机权限
            ret = shutdown(Options);
            // POWEROFF = 0x2 // 关机 // REBOOT = 0x1 // 重启
        }
    }
}

  

标签:关机,IntPtr,闪电,private,dll,ZwShutdownSystem,RtlAdjustPrivilege,CSharp,hLib
From: https://www.cnblogs.com/biltong/p/16847594.html

相关文章