• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c#关机

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

你可以这样来实现:(支持Win XP下的关机)
using System.Runtime.InteropServices;

[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 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 void Reboot()
  {
   DoExitWin( EWX_REBOOT );
  }

                  //点击按钮,执行关机事件
  private void button1_Click(object sender, System.EventArgs e)
  {
   DoExitWin(1);
  }


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
c#写windows服务发布时间:2022-07-10
下一篇:
C#委托事件发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap