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

morijj 2003-09-23 03:38:01
如题,最好给几行代码看看!
...全文
233 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
lxwstar 2003-11-03
  • 打赏
  • 举报
回复
很有用,MARD一下
morijj 2003-09-26
  • 打赏
  • 举报
回复
待兄弟我先慢慢研究一下各位的代码。
RnfShadow 2003-09-25
  • 打赏
  • 举报
回复
你建一个类库,然后把下面的代码全部粘贴进去,覆盖掉里面的。调用这个类的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 );
}



}

}
jeng 2003-09-24
  • 打赏
  • 举报
回复
litp(litp的方法是行得通的

我已经试过

ArLi2003(阿利 路过而已)的方法还没有看明白
ArLi2003 2003-09-24
  • 打赏
  • 举报
回复
过去我在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
morijj 2003-09-24
  • 打赏
  • 举报
回复
才搞明白,以上几位的代码只能在95,98下用,NT XP 不行!
cnhgj 2003-09-23
  • 打赏
  • 举报
回复
http://www.ccw.com.cn/htm/center/prog/02_10_9_6.asp
jeng 2003-09-23
  • 打赏
  • 举报
回复
我来试一试
kuangren 2003-09-23
  • 打赏
  • 举报
回复
本地重新启动要调用winapi,上面 litp(litp) 已经说了!
xzgtysx 2003-09-23
  • 打赏
  • 举报
回复
是否安装.net framework呢?
morijj 2003-09-23
  • 打赏
  • 举报
回复
如litp兄所述,小弟我引用了ExitWindowsEx 执行后看返回值为1.xxxxxx 按理说返回值非0说明函数执行成功了,可是我的windows一点也没有关机的意思,程序也没有出现任何异常。真是奇怪!!
angelior 2003-09-23
  • 打赏
  • 举报
回复
我有一個WMI的,
不過本地計算機實現不了
李天平 2003-09-23
  • 打赏
  • 举报
回复
1.using System.Runtime.InteropServices;

2.
[ 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) ;//关机
morijj 2003-09-23
  • 打赏
  • 举报
回复
我是想在本地实现关机和重新启动,另外,小弟我对 VB 可是不太了解啊,VB 的Dim 代码往C#里怎莫插啊 :-)
acewang 2003-09-23
  • 打赏
  • 举报
回复
Dim ExplorerProcess() As Process
ExplorerProcess = Process.GetProcessesByName("explorer")
ExplorerProcess(0).CloseMainWindow()
_weiKun_ 2003-09-23
  • 打赏
  • 举报
回复
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 ) ;
}
}
}

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧