在C#中如何调用windows的API进行关机操作!!! [转]

http://chenpeng.cnblogs.com/archive/2006/05/24/408313.html

     由于工作需要,自已写了一个局域网多媒体软件.里面涉及到计算机的关机,注销,重启操作.需要用到系统的api.刚开始找了很多资料.还是有错误.后在MSDN中找到了相关的资料.可是是英文的.有一难.经过多次修改.终于写出来了.现在我把调用系统的的API执行关机,注销.重启操作的源码发出来.供大家参考....如有不完善的地方.请大家留言.我方便改正!

     using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading ;
namespace SysLibrary
{
   public class SysConfig
    {
        [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 bool 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);
            return ok;
        }

       public void logoff()
       {
           DoExitWin(EWX_LOGOFF);
       }

       public void reboot()
       {
           DoExitWin(EWX_REBOOT);
       }

       public void Shutdown()
       {
           DoExitWin(EWX_SHUTDOWN);
       }

    }
}

posted @ 2006-10-07 22:24    阅读(524)  评论(1编辑  收藏  举报