如何用C#控制计算机重启或关机?

starchenzhi 2005-09-22 01:29:05
如题,自己在独立开发一个软件,使用.Net架构,就遇到了这样一个难题,当用户的任务完成时,就重启或关闭计算机,这个功能如何实现?用哪个API函数?

另外,如何用C#启动用户指定的程序?
比如:用户在文本框输入"iexplorer.exe",在另一文本输入框键入"http://www.microsoft.com",这时我该如何用C#调用用户指定的程序呢?

预先感谢各位同仁的热情回答,不胜感激!
...全文
321 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
cooljw 2006-02-07
  • 打赏
  • 举报
回复
gz
Kshatriya 2005-09-22
  • 打赏
  • 举报
回复
1.不知道
2.System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "外部程序名称";
p.Start();
luojinat2005 2005-09-22
  • 打赏
  • 举报
回复
关注
vivianfdlpw 2005-09-22
  • 打赏
  • 举报
回复
2.参看 System.Diagnostics.Process类
singlepine 2005-09-22
  • 打赏
  • 举报
回复
Imports System
Imports System.Text
Imports System.Diagnostics
Imports System.Runtime.InteropServices

Public Class WindowsController
Public Enum RestartOptions
LogOff = 0
PowerOff = 8
Reboot = 2
ShutDown = 1
Suspend = -1
Hibernate = -2
End Enum

Public Structure LUID
Dim LowPart As Integer
Dim HighPart As Integer
End Structure

Public Structure LUID_AND_ATTRIBUTES

Dim pLuid As LUID

Dim Attributes As Integer
End Structure


Public Structure TOKEN_PRIVILEGES

Dim PrivilegeCount As Integer

Dim Privileges As LUID_AND_ATTRIBUTES
End Structure

Private Const TOKEN_ADJUST_PRIVILEGES = &H20
Private Const TOKEN_QUERY = &H8
Private Const SE_PRIVILEGE_ENABLED = &H2
Private Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000
Private Const EWX_FORCE = 4
Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As IntPtr
Declare Function FreeLibrary Lib "kernel32" (ByVal hLibModule As IntPtr) As Integer
Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As IntPtr, ByVal lpProcName As String) As IntPtr
Declare Function SetSuspendState Lib "Powrprof" (ByVal Hibernate As Integer, ByVal ForceCritical As Integer, ByVal DisableWakeEvent As Integer) As Integer
Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As IntPtr, ByVal DesiredAccess As Integer, ByRef TokenHandle As IntPtr) As Integer
Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, ByRef lpLuid As LUID) As Integer
Declare Function AdjustTokenPrivileges Lib "advapi32.dll" (ByVal TokenHandle As IntPtr, ByVal DisableAllPrivileges As Integer, ByRef NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Integer, ByRef PreviousState As TOKEN_PRIVILEGES, ByRef ReturnLength As Integer) As Integer
Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Integer, ByVal dwReserved As Integer) As Integer
Declare Function FormatMessage Lib "kernel32" Alias "FormatMessageA" (ByVal dwFlags As Integer, ByVal lpSource As IntPtr, ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByVal lpBuffer As StringBuilder, ByVal nSize As Integer, ByVal Arguments As Integer) As Integer

Public Sub ExitWindows(ByVal how As RestartOptions, ByVal force As Boolean)
Select Case how
Case RestartOptions.Suspend
SuspendSystem(False, force)
Case RestartOptions.Hibernate
SuspendSystem(True, force)
Case Else
ExitWindows(Convert.ToInt32(how), force)
End Select
End Sub

Protected Sub ExitWindows(ByVal how As Integer, ByVal force As Boolean)
EnableToken("SeShutdownPrivilege")
If force Then how = how Or EWX_FORCE
If (ExitWindowsEx(how, 0) = 0) Then Throw New PrivilegeException(FormatError(Marshal.GetLastWin32Error()))
End Sub

Protected Sub EnableToken(ByVal privilege As String)
If Not CheckEntryPoint("advapi32.dll", "AdjustTokenPrivileges") Then Return
Dim tokenHandle As IntPtr = IntPtr.Zero
Dim privilegeLUID = New LUID()
Dim newPrivileges = New TOKEN_PRIVILEGES()
Dim tokenPrivileges As TOKEN_PRIVILEGES
If (OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, tokenHandle)) = 0 Then Throw New PrivilegeException(FormatError(Marshal.GetLastWin32Error()))
If (LookupPrivilegeValue("", privilege, privilegeLUID)) = 0 Then Throw New PrivilegeException(FormatError(Marshal.GetLastWin32Error()))
tokenPrivileges.PrivilegeCount = 1
tokenPrivileges.Privileges.Attributes = SE_PRIVILEGE_ENABLED
tokenPrivileges.Privileges.pLuid = privilegeLUID
Dim Size As Integer = 4
If (AdjustTokenPrivileges(tokenHandle, 0, tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), newPrivileges, Size)) = 0 Then Throw New PrivilegeException(FormatError(Marshal.GetLastWin32Error()))
End Sub

Protected Sub SuspendSystem(ByVal hibernate As Boolean, ByVal force As Boolean)
If Not CheckEntryPoint("powrprof.dll", "SetSuspendState") Then Throw New PlatformNotSupportedException("The SetSuspendState method is not supported on this system!")
SetSuspendState(Convert.ToInt32(IIf(hibernate, 1, 0)), Convert.ToInt32(IIf(force, 1, 0)), 0)
End Sub

Protected Function CheckEntryPoint(ByVal library As String, ByVal method As String) As Boolean
Dim libPtr As IntPtr = LoadLibrary(library)
If Not libPtr.Equals(IntPtr.Zero) Then
If Not GetProcAddress(libPtr, method).Equals(IntPtr.Zero) Then
FreeLibrary(libPtr)
Return True
End If
FreeLibrary(libPtr)
End If
Return False
End Function

Protected Function FormatError(ByVal number As Integer) As String
Dim Buffer = New StringBuilder(255)
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, number, 0, Buffer, Buffer.Capacity, 0)
Return Buffer.ToString()
End Function
End Class

Public Class PrivilegeException
Inherits Exception

Public Sub New()
MyBase.New()
End Sub

Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class

例如实现注销功能:
Dim shutdown As New WindowsController()
shutdown.ExitWindows(shutdown.RestartOptions.LogOff, False)
vivianfdlpw 2005-09-22
  • 打赏
  • 举报
回复
使用C#调用Win32 API实现系统重启和关机
http://www.chinaaspx.com/comm/dotnetbbs/Showtopic.aspx?Forum_ID=6&Id=182694
jinjazz 2005-09-22
  • 打赏
  • 举报
回复

你可以这样来实现:(支持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 mflag, 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 mflag )
{
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( mflag, 0 );
}

public void Reboot()
{
DoExitWin( EWX_REBOOT );
}

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

110,539

社区成员

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

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

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