C#下如何实现关机和重新启动

主  题:  C#下如何实现关机和重新启动?
作  者:  morijj (北极光)
等  级:  ^
信 誉 值:  100
所属论坛:  .NET技术 C#
问题点数:  50
回复次数:  15
发表时间:  2003-09-23 15:31:50

如题,最好给几行代码看看!



回复人: weiKun(Virus) ( 五级(中级)) 信誉:100 2003-09-23 15:49:00 得分:0

private void button1_Click(object sender, System.EventArgs e)
{
    //定义连接远程计算机的一些选项
    ConnectionOptions options = new ConnectionOptions();
    options.Username = textBox2.Text;
    options.Password = textBox3.Text;
    ManagementScope scope = new ManagementScope("\\\\" + textBox1.Text + "\\root\\cimv2", options);
    try
    {
        //用给定管理者用户名和口令连接远程的计算机
        scope.Connect();
        System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem");
        ManagementObjectSearcher query1 = new ManagementObjectSearcher(scope, oq);
        //得到WMI控制
        ManagementObjectCollection queryCollection1 = query1.Get();
        foreach (ManagementObject mo in queryCollection1)
        {
            string[] ss = { "" };
            //重启远程计算机
            mo.InvokeMethod("Reboot", ss);
        }
    }
    //报错
    catch (Exception ee)
    {
        MessageBox.Show("连接" + textBox1.Text + "出错,出错信息为:" + ee.Message);
    }
}
}

回复人: acewang(^o^) ( 一星(中级)) 信誉:100 2003-09-23 15:54:00 得分:0

Dim ExplorerProcess() As Process
ExplorerProcess = Process.GetProcessesByName("explorer")
ExplorerProcess(0).CloseMainWindow()

回复人: morijj(北极光) ( 一级(初级)) 信誉:100 2003-09-23 16:34:00 得分:0

我是想在本地实现关机和重新启动,另外,小弟我对 VB 可是不太了解啊,VB 的Dim 代码往C#里怎莫插啊 😃

回复人: litp(litp) ( 一级(初级)) 信誉:100 2003-09-23 16:39:00 得分:0

1.using System.Runtime.InteropServices;

using System.Runtime.InteropServices;

[DllImport("user32")]
public static extern long ExitWindowsEx(long uFlags, long dwReserved);
[DllImport("shell32")]
public static extern long ShellAbout(long uFlags, long dwReserved);

long dwReserved;
const int LOGOFF = 0;
const int SHUTDOWN = 1;
const int REBOOT = 2;

sh = ExitWindowsEx(REBOOT, dwReserved); //重启
sh = ExitWindowsEx(LOGOFF, dwReserved) //注销
h = ExitWindowsEx(SHUTDOWN, dwReserved);//关机

回复人: zhouzhouzhou(人生程序) ( 三级(初级)) 信誉:100 2003-09-23 18:06:00 得分:0

我有一個WMI的,
不過本地計算機實現不了

回复人: morijj(北极光) ( 一级(初级)) 信誉:100 2003-09-23 19:45:00 得分:0

如litp兄所述,小弟我引用了ExitWindowsEx 执行后看返回值为1.xxxxxx 按理说返回值非0说明函数执行成功了,可是我的windows一点也没有关机的意思,程序也没有出现任何异常。真是奇怪!!

回复人: xzgtysx(海带) ( 二级(初级)) 信誉:100 2003-09-23 20:43:00 得分:0

是否安装.net framework呢?

回复人: kuangren(今天逃课~) ( 三级(初级)) 信誉:100 2003-09-23 21:36:00 得分:0

本地重新启动要调用winapi,上面 litp(litp) 已经说了!

回复人: jeng(第四只手) ( 二级(初级)) 信誉:98 2003-09-23 22:08:00 得分:0

我来试一试

回复人: cnhgj(戏子.Com?俺真TMD够菜) ( 一星(中级)) 信誉:100 2003-09-23 22:56:00 得分:0

http://www.ccw.com.cn/htm/center/prog/02_10_9_6.asp

回复人: morijj(北极光) ( 一级(初级)) 信誉:100 2003-09-24 03:52:00 得分:0

才搞明白,以上几位的代码只能在95,98下用,NT XP 不行!

回复人: ArLi2003(阿利 路过而已) ( 两星(中级)) 信誉:100 2003-09-24 06:24:00 得分:0

过去我在vb 上做过,在NT 下必须先取得系统操作权限,没空改要是不会发消息给我帮你改成C#:

Option Explicit

Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long
Private Declare Function AdjustTokenPrivileges Lib "advapi32.dll" (ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, PreviousState As Long, ReturnLength As Long) As Long
Private Declare Function GetTokenInformation Lib "advapi32.dll" (ByVal TokenHandle As Long, ByVal TokenInformationClass As Long, TokenInformation As Any, ByVal TokenInformationLength As Long, ReturnLength As Long) As Long
Private Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, ByRef lpLuid As LARGE_INTEGER) As Long
Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
Private Declare Function GetCurrentProcessId Lib "kernel32" () As Long
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Const EWX_LOGOFF = 0 '注销当前用户
Private Const EWX_POWEROFF = 8 '关闭系统并关闭电源
Private Const EWX_SHUTDOWN = 1 '关闭系统使之能安全关闭电源
Private Const EWX_REBOOT = 2 '关闭系统并重启
Private Const EWX_FORCE = 4 '应用程序强制关闭
Private Const EWX_FORCEIFHUNG = 16 '如果应用程序已挂起,强制关闭
Private Const SE_PRIVILEGE_ENABLED = &H2
Private Const SE_PRIVILEGE_ENABLED_BY_DEFAULT = &H1
Private Const SE_PRIVILEGE_USED_FOR_ACCESS = &H80000000
Private Const TOKEN_ADJUST_PRIVILEGES = &H20
Private Const TOKEN_QUERY_SOURCE = &H10
Private Const TOKEN_QUERY = &H8
Private Const ANYSIZE_ARRAY = 1
Private Const SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
Private Const PROCESS_SET_INFORMATION = &H200
Private Const PROCESS_QUERY_INFORMATION = &H400
Private Type LARGE_INTEGER
    lowpart As Long
    highpart As Long
End Type
Private Type LUID
    lowpart As Long
    highpart As Long
End Type
Private Type LUID_AND_ATTRIBUTES
    pLuid As LUID
    Attributes As Long
End Type
Private Type TOKEN_PRIVILEGES
    PrivilegeCount As Long
    Privileges(0) As LUID_AND_ATTRIBUTES
End Type
Public Sub exitWin2k(ByVal Obj As String)
    On Error GoTo Win98Off

    Dim lAPIReturn As Long
    Dim tTOKPRI As TOKEN_PRIVILEGES
    Dim tLUID As LUID
    Dim tLarInt As LARGE_INTEGER
    Dim lRequired As Long
    Dim hTokHan As Long
    Dim hProcess As Long
    If LookupPrivilegeValue(vbNullString, SE_SHUTDOWN_NAME, tLarInt) = 0 Then
        'MsgBox "Get LUID error!", vbOKOnly, "Error"
        GoTo Win98Off
    End If
    tLUID.highpart = tLarInt.highpart
    tLUID.lowpart = tLarInt.lowpart
    tTOKPRI.PrivilegeCount = 1
    tTOKPRI.Privileges(0).Attributes = SE_PRIVILEGE_ENABLED
    tTOKPRI.Privileges(0).pLuid = tLUID
    hProcess = GetCurrentProcess()
    lAPIReturn = OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES + TOKEN_QUERY, hTokHan)
    lAPIReturn = AdjustTokenPrivileges(hTokHan, 0, tTOKPRI, Len(tTOKPRI), 0, 0)
    
    Select Case Obj
        Case "关机"
            lAPIReturn = ExitWindowsEx(EWX_FORCE + EWX_POWEROFF, 0)
        Case Else
            ' lAPIReturn = ExitWindowsEx(EWX_FORCEIFHUNG, 0)
            ' lAPIReturn = ExitWindowsEx(EWX_SHUTDOWN, 0)
            ' lAPIReturn = ExitWindowsEx(EWX_LOGOFF, 0)
            ' lAPIReturn = ExitWindowsEx(EWX_SHUTDOWN, 0)
            ' lAPIReturn = ExitWindowsEx(EWX_POWEROFF, 0)
            ' lAPIReturn = ExitWindowsEx(EWX_REBOOT, 0)
            ' lAPIReturn = ExitWindowsEx(EWX_FORCE, 0)
    End Select

    If lAPIReturn = 0 Then
        'MsgBox "Function calling error!", vbOKOnly, "错误"
    End If
    lAPIReturn = CloseHandle(hTokHan)

Win98Off:
    lAPIReturn = ExitWindowsEx(EWX_FORCE + EWX_POWEROFF, 0)
    End
End Sub

你也可以用(XP or higher only):

shutdown /r /t 0 /f

回复人: jeng(第四只手) ( 二级(初级)) 信誉:98 2003-09-24 22:58:00 得分:0

litp(litp的方法是行得通的

我已经试过

ArLi2003(阿利 路过而已)的方法还没有看明白

回复人: RnfShadow() ( 一级(初级)) 信誉:100 2003-09-25 00:59:00 得分:0

你建一个类库,然后把下面的代码全部粘贴进去,覆盖掉里面的。调用这个类的Reboot就是重启,PowerOff就是关机,LogoOff就是注销!!

using System;
using System.Runtime.InteropServices;

namespace ExitWindows
{
    public class Class1
    {
        [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 static 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 static void Reboot()
        {
            DoExitWin(EWX_FORCE | EWX_REBOOT);
        }

        public static void PowerOff()
        {
            DoExitWin(EWX_FORCE | EWX_POWEROFF);
        }

        public static void LogoOff()
        {
            DoExitWin(EWX_FORCE | EWX_LOGOFF);
        }
    }
}

回复人: morijj(北极光) ( 一级(初级)) 信誉:100 2003-09-26 01:24:00 得分:0

待兄弟我先慢慢研究一下各位的代码。

Contributors: FHL