namespace ShutDownTest {
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Security.Principal;
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public struct LUID
{
public uint LowPart;
public uint HighPart;
};
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
public struct TOKEN_PRIVILEGES
{
public uint PrivilegeCount;
public LUID Luid;
public uint Attributes;
};
public class PlatformImport
{
[DllImport("advapi32", CharSet=CharSet.Auto)]
public static extern bool LookupPrivilegevalue (string sysname,string privname,ref LUID luid);
[DllImport("advapi32", CharSet=CharSet.Auto)]
public static extern bool AdjustTokenPrivileges(IntPtr handle, bool dsall,ref TOKEN_PRIVILEGES newstate,int len, IntPtr oldstate,IntPtr retlen);
[DllImport("kernel32.dll")]
public static extern int GetLastError();
[DllImport("user32.dll")]
public static extern bool ExitWindowsEx(int uFlags, int dwReason);
}
public class Form1 : Form
{
private Button button1;
public Form1()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
this.button1.Location = new Point(136, 112);
= "button1";
this.button1.Size = new Size(80, 24);
this.button1.TabIndex = 0;
this.button1.Text = "Shut Down";
this.button1.Click += new EventHandler(this.button1_Click);
this.AutoScaleBaseSize = new Size(6, 14);
this.ClientSize = new Size(292, 273);
this.Controls.Add(button1);
= "Form1";
this.Text = "shutdown test";
this.ResumeLayout(false);
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
IntPtr token = identity.Token;
IntPtr luid = (IntPtr)0;
IntPtr previousState = (IntPtr)0;
IntPtr previousStateLength = (IntPtr)0;
LUID privilegeId = new LUID ();
PlatformImport.LookupPrivilegevalue ("", "SeShutdownPrivilege", ref privilegeId);
TOKEN_PRIVILEGES privileges = new TOKEN_PRIVILEGES(); privileges.PrivilegeCount = 1;
privileges.Luid = privilegeId;
privileges.Attributes = 2;
PlatformImport.AdjustTokenPrivileges (token, false, ref privileges, Marshal.SizeOf(privileges), previousState, previousStateLength);
if (PlatformImport.GetLastError() != 0) return;
if(!(PlatformImport.ExitWindowsEx(0x01 | 0x04, 0))) return;
}
}
}C#实现关机的功能
原创
©著作权归作者所有:来自51CTO博客作者biyusr216的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
C#实现登录功能
C#实现登录功能
职场 C# 登录 休闲 -
C# 实现录音功能
用C#实现录音的功能
职场 C# 休闲 录音 -
C#实现系统热键的功能
利用
c# ide 热键 mysql数据库 sed -
C#实现语音朗读功能
第一步:新建项目 TTS(从文本到语音(TextToSpeech)) 第二步:添加
desktop microsoft 新建项目 -
从 0 到上线、长期运行、后续更新的**全流程**(适配 CentOS 服务器)
如果服务器启用了防火墙或 SELinux,本文下面会给出对应处理方式。
服务器 centos linux docker ico
















