当前位置:编程学习 > C#/ASP.NET >>

C#关闭电脑谁有源码????????

大家请帮个忙,等着急用C#关闭电脑 。。。。。。。要快要快
--------------------编程问答-------------------- [DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)]
        private static extern int ExitWindowsEx(int uFlags, int dwReserved);
        //注销计算机
        public void logout()
        {
            ExitWindowsEx(0, 0);
        }
       //关闭计算机
        public void closepc()
        {
            //创建访问控制本地系统进程的对象实例
            System.Diagnostics.Process myprocess = new System.Diagnostics.Process();
            myprocess.StartInfo.FileName = "cmd.exe";
            myprocess.StartInfo.UseShellExecute = false;
            myprocess.StartInfo.RedirectStandardInput = true;
            myprocess.StartInfo.RedirectStandardOutput = true;
            myprocess.StartInfo.RedirectStandardError = true;
            myprocess.StartInfo.CreateNoWindow = true;
            myprocess.Start();
            myprocess.StandardInput.WriteLine("shutdown -s -t 0");
        }
        //重新启动计算机
        public void afreshstartpc()
        {
            //创建访问控制本地系统进程的对象实例
            System.Diagnostics.Process myprocess = new System.Diagnostics.Process();
            myprocess.StartInfo.FileName = "cmd.exe";
            myprocess.StartInfo.UseShellExecute = false;
            myprocess.StartInfo.RedirectStandardInput = true;
            myprocess.StartInfo.RedirectStandardOutput = true;
            myprocess.StartInfo.RedirectStandardError = true;
            myprocess.StartInfo.CreateNoWindow = true;
            myprocess.Start();
            myprocess.StandardInput.WriteLine("shutdown -r -t 0");
        } --------------------编程问答-------------------- 楼上已经给了。不过Vista的时候注意一下权限问题,用户权限不够关不了 --------------------编程问答-------------------- 简单
  调用系统自带的那些.EXE文件。 --------------------编程问答--------------------
引用 1 楼 xm18love 的回复:
[DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)] 
        private static extern int ExitWindowsEx(int uFlags, int dwReserved); 
        //注销计算机 
        public void logout() 
        { 
            ExitWindowsEx(0, 0); 
        } 
      //关闭计算机 
        public void closepc() 
        { 
            //创建访问控制本地系统进程的对象实例 
        …



主要是使用命令行  shutdown
-r重啟
-s關機
-t時間  --------------------编程问答-------------------- ding --------------------编程问答-------------------- 好东东。。。高手呀
--------------------编程问答-------------------- 解决了不来拿,,不着急,,, --------------------编程问答-------------------- 有答案了!~~~~~~~~~~~~~~~
dos命令我都记不住了!~ --------------------编程问答-------------------- 果然 是高手啊,不服不行 --------------------编程问答-------------------- 不错 --------------------编程问答-------------------- 学习了 --------------------编程问答--------------------

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;

namespace WindowsApplication1
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();

//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null) 
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.SuspendLayout();
// 
// button1
// 
this.button1.Location = new System.Drawing.Point(24, 24);
this.button1.Name = "button1";
this.button1.TabIndex = 0;
this.button1.Text = "关机";
this.button1.Click += new System.EventHandler(this.button1_Click);
// 
// button2
// 
this.button2.Location = new System.Drawing.Point(112, 24);
this.button2.Name = "button2";
this.button2.TabIndex = 1;
this.button2.Text = "注销";
this.button2.Click += new System.EventHandler(this.button2_Click);
// 
// button3
// 
this.button3.Location = new System.Drawing.Point(208, 24);
this.button3.Name = "button3";
this.button3.TabIndex = 2;
this.button3.Text = "重新启动";
this.button3.Click += new System.EventHandler(this.button3_Click);
// 
// Form1
// 
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(292, 70);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main() 
{
Application.Run(new Form1());
}

#region 微软提供的关机接口 调用系统的 kernel32.dll  advapi32.dll user32.dll 实现的关机
[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 DoFlag, 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;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
internal const int EWX_FORCEIFHUNG = 0x00000010;

private static bool DoExitWin(int DoFlag)
{
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(DoFlag, 0);
return ok;
}

/**//// <summary>
/// 重新启动
/// </summary>
public static bool Reboot()
{
return DoExitWin(EWX_FORCE | EWX_REBOOT);
}

/**//// <summary>
/// 关机
/// </summary>
public static bool PowerOff()
{
return DoExitWin(EWX_FORCE | EWX_POWEROFF);
}

/**//// <summary>
/// 注销
/// </summary>
public static bool LogOff()
{
return DoExitWin(EWX_FORCE | EWX_LOGOFF);
}
#endregion

private void button2_Click(object sender, System.EventArgs e)
{
LogOff();
}

private void button1_Click(object sender, System.EventArgs e)
{
PowerOff();
}

private void button3_Click(object sender, System.EventArgs e)
{
 Reboot();
}
}
}


--------------------编程问答-------------------- Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
string commandLine = String.Empty;
switch (option)
{
       case Program.OptionType.isCancel:
              commandLine += @"shutdown /a";
              break;
       case Program.OptionType.isLogoff:
              commandLine += @"shutdown /f /l /t" + BLANK + interval;
              break;
       case Program.OptionType.isRestart:
              commandLine += @"shutdown /f /r /t" + BLANK + interval;
               break;
       case Program.OptionType.isShutdown:
              commandLine += @"shutdown /f /s /t" + BLANK + interval;
              break;
       }
       proc.StandardInput.WriteLine(commandLine);
或  [DllImport("user32.dll")]
        static extern bool ExitWindowsEx(ExitWindows uFlags, ShutdownReason dwReason);

--------------------编程问答-------------------- using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Runtime.InteropServices;
namespace auto
{
    public partial class Form1 : Form
    {
        private long dwReserved = 0;
        //const int SHUTDOWN = 1;
        //const int REBOOT = 2;
        private const int LOGOFF = 0;
        private long sh;
        private static int act=0;
        public Form1()
        {
            InitializeComponent();
        }

       //声明系统API
        [DllImport ("user32")]
        public static extern long ExitWindowsEx(long uFlags, long dwReserved);
    
        private void Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Relogin_Click(object sender, EventArgs e)
        {
            sh = ExitWindowsEx(LOGOFF, dwReserved);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //用系统时间初始化
            timer2.Enabled = true;
            
        }
        public static void Action(int choice)
        {
            try
            {
                SelectQuery query = new SelectQuery("select name from Win32_OperatingSystem where primary=true");
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

                foreach (ManagementObject os in searcher.Get())
                {
                    //打开权限
                    os.Scope.Options.EnablePrivileges = true;
                    ManagementBaseObject outparams;
                    switch (choice)
                    {
                        case 1: outparams = os.InvokeMethod("Shutdown", null, null);
                            break;
                        case 2: outparams = os.InvokeMethod("Reboot", null, null);
                            break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                //接受当前日期和时间,用于及时显示
                string CurrDateTime = System.DateTime.Now.ToString();
                textBox1.Text = SetupDate.Text.ToString() + " " + SetupTime.Text.ToString();
                textBox2.Text = SetupDate.Text.ToString() + " " + SetupTime.Text.ToString();
                //随时检测设定的关机日期和时间是否有效
                if (CurrDateTime == textBox2.Text)
                {
                    Action(act);
                    timer1.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            SysTime.Text = System.DateTime.Now.ToString();
        }

        private void Shutdown_Click(object sender, EventArgs e)
        {
            if(this.checkBox1.Checked==true)
            {
                timer1.Enabled=true;
                label1.Text="系统将在";
                label1.Visible=true;
                label2.Text="时准时关机!";
                label2.Visible =true;
                textBox1.Visible=true;
                act =1;
            }
            else 
            {
              Action (1);
            }
        }

        private void Reboot_Click(object sender, EventArgs e)
        {
            if (this.checkBox1.Checked ==true)
            {
                timer1.Enabled=true;
                label3.Text="系统将在";
                label3 .Visible=true;
                label4.Text="时准时启动";
                label4.Visible=true;
                textBox2.Visible=true;
                act=2;
            }
            else
            {
                Action(2);
            }
                

        }

        private void Form1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.axWindowsMediaPlayer1.URL = this.openFileDialog1.FileName;
            }
        }

        private void 打开mp3文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.axWindowsMediaPlayer1.URL = this.openFileDialog1.FileName;
            }
        }


        }

    }
定时关机,重启。  从别人那弄的,你自己研究下吧。。 --------------------编程问答-------------------- 正解不多。12楼的靠点谱。 --------------------编程问答--------------------
引用 13 楼 wuyq11 的回复:
Process proc = new Process(); 
proc.StartInfo.FileName = "cmd.exe"; 
proc.StartInfo.UseShellExecute = false; 
proc.StartInfo.RedirectStandardError = true; 
proc.StartInfo.RedirectStandardInput = true; 
proc.StartInfo.CreateNoWindow = true; 
proc.StartInfo.RedirectStandardOutput = true; 
proc.Start(); 
string commandLine = String.Empty; 
switch (option) 

      case Program.OptionTyp…


顶,, --------------------编程问答-------------------- 12正解.
不过其他的也不能算错.
懒得用api直接调用shutdown也不失为一个好办法. --------------------编程问答-------------------- 您看看吧,我从网上的,代码太长了,还是自己去看吧!进入 --------------------编程问答-------------------- 核心代码: Process.start("shutdown -s -t 0"); --------------------编程问答-------------------- jh --------------------编程问答-------------------- mark --------------------编程问答-------------------- API API 
坚决支持API  --------------------编程问答-------------------- 关机的类:
http://blog.csdn.net/null1/archive/2008/11/03/3208145.aspx --------------------编程问答--------------------
12楼的不行?
提示无法在"advapi32.dll"中找到“lookupprivilege”的入口点,
这啥意思?
对api不懂。。。。
--------------------编程问答-------------------- 关注! --------------------编程问答--------------------

高手呀 --------------------编程问答-------------------- mark !

shutdown - s -t 0 --------------------编程问答-------------------- using System.Runtime.InteropServices;

  [Flags]

  public enum ExitWindows : uint

  {

  LogOff = 0x00, //注销

  ShutDown = 0x01, //关机

  Reboot = 0x02, //重启

  Force = 0x04,

  PowerOff = 0x08,

  ForceIfHung = 0x10

  }

  [Flags]

  public enum ShutdownReason : uint

  {

  MajorApplication = 0x00040000,

  MajorHardware = 0x00010000,

  MajorLegacyApi = 0x00070000,

  MajorOperatingSystem = 0x00020000,

  MajorOther = 0x00000000,

  MajorPower = 0x00060000,

  MajorSoftware = 0x00030000,

  MajorSystem = 0x00050000,

  MinorBlueScreen = 0x0000000F,

  MinorCordUnplugged = 0x0000000b,

  MinorDisk = 0x00000007,

  MinorEnvironment = 0x0000000c,

  MinorHardwareDriver = 0x0000000d,

  MinorHotfix = 0x00000011,

  MinorHung = 0x00000005,

  MinorInstallation = 0x00000002,

  MinorMaintenance = 0x00000001,

  MinorMMC = 0x00000019,

  MinorNetworkConnectivity = 0x00000014,

  MinorNetworkCard = 0x00000009,

  MinorOther = 0x00000000,

  MinorOtherDriver = 0x0000000e,

  MinorPowerSupply = 0x0000000a,

  MinorProcessor = 0x00000008,

  MinorReconfig = 0x00000004,

  MinorSecurity = 0x00000013,

  MinorSecurityFix = 0x00000012,

  MinorSecurityFixUninstall = 0x00000018,

  MinorServicePack = 0x00000010,

  MinorServicePackUninstall = 0x00000016,

  MinorTermSrv = 0x00000020,

  MinorUnstable = 0x00000006,

  MinorUpgrade = 0x00000003,

  MinorWMI = 0x00000015,

  FlagUserDefined = 0x40000000,

  FlagPlanned = 0x80000000

  }

  [DllImport("user32.dll")]

  static extern bool ExitWindowsEx(ExitWindows uFlags, ShutdownReason dwReason);

  [STAThread]

  static void Main(string[] args)

  {

  ExitWindowsEx(ExitWindows.ShutDown, ShutdownReason.MajorOther & ShutdownReason.MinorOther);


  //这个语句将实现计算机注销操作

  }
--------------------编程问答-------------------- using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace SharedLib
{

    /// <summary>
    /// Windows系统正常或快速关机
    /// </summary>

    public class Shutdown
    {
        #region
        [DllImport("ntdll.dll", SetLastError = true)]
        private static extern int RtlAdjustPrivilege(int Privilege, bool Enable, bool CurrentThread, out bool Enabled);

        [DllImport("ntdll.dll", SetLastError = true)]
        private static extern int NtShutdownSystem(int ShutdownAction);

        private const int SE_SHUTDOWN_PRIVILEGE = 19;
        private const int SHUTDOWN = 0;
        private const int RESTART = 1;
        private const int POWEROFF = 2;

        /// <summary>
        /// 快速关机或重启动
        /// </summary>
        /// <param name="action">为0时关机,为1时重新启动</param>
        public static void TurboShutdown(int action)
        {
            bool e;
            int tmp;
            tmp=RtlAdjustPrivilege(SE_SHUTDOWN_PRIVILEGE, true, false, out e);
            switch (action)
            {
                case 0:
                    tmp = NtShutdownSystem(SHUTDOWN); //快速关机
                    break;
                case 1:
                    tmp = NtShutdownSystem(RESTART);    //快速重启动
                    break;
                default:
                    break;
            }
        }
        #endregion

        #region
        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        private struct TokPriv1Luid
        {
            public int Count;
            public long Luid;
            public int Attr;
        }
        [DllImport("kernel32.dll", ExactSpelling = true)]
        private static extern IntPtr GetCurrentProcess();

        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        private static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);

        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);

        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        private static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);

        [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
        private static extern bool ExitWindowsEx(int flg, int rea);

        private const int SE_PRIVILEGE_ENABLED = 0x00000002;
        private const int TOKEN_QUERY = 0x00000008;
        private const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
        private const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
        private const int EWX_LOGOFF = 0x00000000;
        private const int EWX_SHUTDOWN = 0x00000001;
        private const int EWX_REBOOT = 0x00000002;
        private const int EWX_FORCE = 0x00000004;
        private const int EWX_POWEROFF = 0x00000008;
        private const int EWX_FORCEIFHUNG = 0x00000010;

        /// <summary>
        /// 正常关机或重启动或注销
        /// </summary>
        /// <param name="action">为0时关机,为1时重新启动,为2时注销</param>
        public static void NormalShutdown(int action)
        {
            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);
            switch (action)
            {
                case 0:
                    ok = ExitWindowsEx(EWX_SHUTDOWN, 0);  //关机
                    break;
                case 1:
                    ok = ExitWindowsEx(EWX_REBOOT, 0);    //重新启动
                    break;
                case 2:
                    ok = ExitWindowsEx(EWX_LOGOFF, 0);    //注销
                    break;
                default:
                    break;
            }
        }
        #endregion
    }


} --------------------编程问答-------------------- 学习!牛X
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,