how to reboot, or shutdown the computer ?

  • Thread starter Thread starter =?ISO-8859-1?Q?Herbert_VON_GR=DCNENWALD?=
  • Start date Start date
In C#, it is still the same ExitWindowsEx API call.

class Class1
{
[DllImport("user32.dll")]
static extern bool ExitWindowsEx(uint uFlags, uint
dwReason);

[STAThread]
static void Main(string[] args)
{
ExitWindowsEx(1, 0); //this will cause the system to
shut down.
}
}

uFlags
4 = Force any applications to quit instead of prompting the user to close
them.
0 = Log off the network.
8 = Shut down the system and, if possible, turn the computer off.
2 = Perform a full reboot of the system.
1 = Shut down the system.
 
Lebesgue said:
In C#, it is still the same ExitWindowsEx API call.

class Class1
{
[DllImport("user32.dll")]
static extern bool ExitWindowsEx(uint uFlags, uint
dwReason);

[STAThread]
static void Main(string[] args)
{
ExitWindowsEx(1, 0); //this will cause the system to
shut down.
}
}

uFlags
4 = Force any applications to quit instead of prompting the user to close
them.
0 = Log off the network.
8 = Shut down the system and, if possible, turn the computer off.
2 = Perform a full reboot of the system.
1 = Shut down the system.


in c++ it was ExitWindowsEx()

thanks

thanks

so there is no C# class that encapsulates this API ?
 
Herbert,

No, there is not. You could use the classes in the System.Management
namespace and access the method on the WMI class, but it is just as
roundabout as using the function through the P/Invoke layer.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Herbert VON GRÜNENWALD said:
Lebesgue said:
In C#, it is still the same ExitWindowsEx API call.

class Class1
{
[DllImport("user32.dll")]
static extern bool ExitWindowsEx(uint uFlags, uint
dwReason);

[STAThread]
static void Main(string[] args)
{
ExitWindowsEx(1, 0); //this will cause the system
to
shut down.
}
}

uFlags
4 = Force any applications to quit instead of prompting the user to
close
them.
0 = Log off the network.
8 = Shut down the system and, if possible, turn the computer off.
2 = Perform a full reboot of the system.
1 = Shut down the system.


in c++ it was ExitWindowsEx()

thanks

thanks

so there is no C# class that encapsulates this API ?
 
Herbert VON GRÜNENWALD said:
Lebesgue said:
In C#, it is still the same ExitWindowsEx API call.

class Class1
{
[DllImport("user32.dll")]
static extern bool ExitWindowsEx(uint uFlags, uint
dwReason);

[STAThread]
static void Main(string[] args)
{
ExitWindowsEx(1, 0); //this will cause the system
to
shut down.
}
}

uFlags
4 = Force any applications to quit instead of prompting the user to
close
them.
0 = Log off the network.
8 = Shut down the system and, if possible, turn the computer off.
2 = Perform a full reboot of the system.
1 = Shut down the system.


in c++ it was ExitWindowsEx()

thanks

thanks

so there is no C# class that encapsulates this API ?

Yes there is, you could use System.Management classes and the WMI class
Win32_OperatingSystem.

public static void Main() {
ManagementBaseObject outParams = null;
ManagementClass os = new ManagementClass("Win32_OperatingSystem");
os.Get();
os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown");
inParams["Flags"] = "1"; // System shutdown
inParams["Reserved"] = "0";
foreach (ManagementObject mo in os.GetInstances())
outParams = mo.InvokeMethod("Win32Shutdown",
inParams, null);

Willy.
 
Lebesgue said:
In C#, it is still the same ExitWindowsEx API call.

class Class1
{
[DllImport("user32.dll")]
static extern bool ExitWindowsEx(uint uFlags, uint
dwReason);

[STAThread]
static void Main(string[] args)
{
ExitWindowsEx(1, 0); //this will cause the system
to
shut down.
}
}

uFlags
4 = Force any applications to quit instead of prompting the user to close
them.
0 = Log off the network.
8 = Shut down the system and, if possible, turn the computer off.
2 = Perform a full reboot of the system.
1 = Shut down the system.


Herbert VON GRÜNENWALD said:
in c++ it was ExitWindowsEx()

thanks

Did you test your code? If you actualy did you would have noticed that this
doesn't work.
The reason is simple, you have to enable the "SeShutdown" privilege using
PInvoke, something more complicated than calling ExitWindowsEx.

Willy.
 
Nicholas Paldino said:
Herbert,

No, there is not. You could use the classes in the System.Management
namespace and access the method on the WMI class, but it is just as
roundabout as using the function through the P/Invoke layer.

Hope this helps.

Nicholas ,

I have to disagree, because the simple PInvoke snip is not enough to invoke
a shutdown, you need to enable the SeShutdown privilege for this to work,
and this is non-trivial using PInvoke. System.Management is definitely the
way to go.

Willy.
 
Willy said:
In C#, it is still the same ExitWindowsEx API call.

class Class1
{
[DllImport("user32.dll")]
static extern bool ExitWindowsEx(uint uFlags, uint
dwReason);

[STAThread]
static void Main(string[] args)
{
ExitWindowsEx(1, 0); //this will cause the system
to
shut down.
}
}

uFlags
4 = Force any applications to quit instead of prompting the user to close
them.
0 = Log off the network.
8 = Shut down the system and, if possible, turn the computer off.
2 = Perform a full reboot of the system.
1 = Shut down the system.


in c++ it was ExitWindowsEx()

thanks

Did you test your code? If you actualy did you would have noticed that this
doesn't work.
The reason is simple, you have to enable the "SeShutdown" privilege using
PInvoke, something more complicated than calling ExitWindowsEx.

Willy.
yes, it dosn't work, the version that works is (a little bit more
longuer...):

using System;
using System.Runtime.InteropServices;


namespace WINAPIInterface
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class WINAPIProcess
{
public WINAPIProcess()
{
//
// TODO: Add constructor logic here
//
}
[StructLayout(LayoutKind.Sequential)]
public struct ProcessEntry32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)] public string
szExeFile;
};


[DllImport("KERNEL32.DLL")]
public static extern int CreateToolhelp32Snapshot(uint flags, uint
processid);

[DllImport("KERNEL32.DLL")]
public static extern int Process32First(int handle, ref ProcessEntry32
pe);

[DllImport("KERNEL32.DLL")]
public static extern int Process32Next(int handle, ref ProcessEntry32 pe);

[DllImport("KERNEL32.DLL")]
public static extern int CloseHandle(int handle);

public uint SNAPPROCESS = 2;

[DllImport("KERNEL32.DLL")]
public static extern int OpenProcess(uint dwDesiredAccess, int
bInheritHandle, uint dwProcessId);

[StructLayout(LayoutKind.Sequential)]
public class PROCESS_MEMORY_COUNTERS
{
public int cb;
public int PageFaultCount;
public int PeakWorkingSetSize;
public int WorkingSetSize;
public int QuotaPeakPagedPoolUsage;
public int QuotaPagedPoolUsage;
public int QuotaPeakNonPagedPoolUsage;
public int QuotaNonPagedPoolUsage;
public int PagefileUsage;
public int PeakPagefileUsage;
}

[DllImport("psapi.dll")]
public static extern int GetProcessMemoryInfo(int hProcess, [Out]
PROCESS_MEMORY_COUNTERS counters, int size);

[StructLayout(LayoutKind.Sequential)]
public struct LUID
{
public uint LowPart;
public uint HighPart;
};

public const int ANYSIZE_ARRAY = 1;

[StructLayout(LayoutKind.Sequential)]
public struct TOKEN_PRIVILEGES
{
public uint PriviledgeCount;
public LUID Luid;
public uint Attributes;

}

[DllImport("KERNEL32.DLL")]
public static extern int GetCurrentProcess();

[DllImport("advapi32.dll")]
public static extern System.Boolean OpenProcessToken(
int ProcessHandle,
uint DesiredAccess,
ref int Tokenhandle
);

[DllImport("advapi32.dll")]
public static extern System.Boolean LookupPrivilegeValue(
string lpSsytemName,
string lpName,
ref LUID pluid);

[DllImport("advapi32.dll")]
public static extern int AdjustTokenPrivileges(
int TokenHandle,
int DisableAllPrivileges,
[MarshalAs(UnmanagedType.Struct)]ref TOKEN_PRIVILEGES NewState,
int BufferLength,
int PreviousState,
int ReturnLength);

[DllImport("user32.dll")]
public static extern bool ExitWindowsEx(int flg, int rea);

public enum EWX_ENUM
{
EWX_LOGOFF = 0x00000000,
EWX_SHUTDOWN = 0x00000001,
EWX_REBOOT = 0x00000002,
EWX_FORCE = 0x00000004,
EWX_POWEROFF= 0x00000008,
EWX_FORCEIFHUNG = 0x00000010,
EWX_FORCEREBOOT = EWX_REBOOT | EWX_FORCE,
EWX_FORCEIFHUNGREBOOT = EWX_REBOOT | EWX_FORCEIFHUNG,
EWX_FORCESHUTDOWN = EWX_SHUTDOWN | EWX_FORCE,
EWX_FORCEIFHUNGSHUTDOWN = EWX_SHUTDOWN | EWX_FORCEIFHUNG,
EWX_FORCEPOWEROFF = EWX_POWEROFF | EWX_FORCE,
EWX_FORCEIFHUNGPOWEROFF = EWX_POWEROFF | EWX_FORCEIFHUNG,
EWX_FORCELOGOFF = EWX_LOGOFF | EWX_FORCE,
EWX_FORCEIFHUNGLOGOFF = EWX_LOGOFF | EWX_FORCEIFHUNG
}

/// <summary>
/// Takes a snap shot of processes running on the computer, and
searches for a
/// specified process name [name.exe].
/// </summary>
/// <param name="pname">Process name to be searched for.</param>
/// <returns>true if process found and false otherwise.</returns>
public static bool FindProcessByName(string pname)
{

int SnapShot = CreateToolhelp32Snapshot(0x00000002, 0);
ProcessEntry32 pe32 = new ProcessEntry32();
pe32.dwSize = 296;

while(Process32Next(SnapShot, ref pe32) != 0)
{

string xname = pe32.szExeFile.ToString();

if(pname.CompareTo(xname) == 0)
{
CloseHandle(SnapShot);
return true;
}
}
CloseHandle(SnapShot);
return false;
}

public static int GetNumberRunning(string pname)
{
int ProcCount = 0;
int SnapShot = CreateToolhelp32Snapshot(0x00000002, 0);
ProcessEntry32 pe32 = new ProcessEntry32();
pe32.dwSize = 296;
while(Process32Next(SnapShot, ref pe32) != 0)
{
string xname = pe32.szExeFile.ToString();
if(pname.CompareTo(xname) == 0)
{
ProcCount++;
}
}
CloseHandle(SnapShot);
return ProcCount;
}

public static uint GetProcessIdForProcess(string pname)
{
uint procid = 0;
int SnapShot = CreateToolhelp32Snapshot(0x00000002, 0);
ProcessEntry32 pe32 = new ProcessEntry32();
pe32.dwSize = 296;
while(Process32Next(SnapShot, ref pe32) != 0)
{
string xname = pe32.szExeFile.ToString();
if(pname.CompareTo(xname) == 0)
{
procid = pe32.th32ProcessID;
break;
}
}
CloseHandle(SnapShot);
return procid;
}

public static int GetMemoryUsageForProcess(string pname)
{
try
{
return GetMemoryUsageForProcess(GetProcessIdForProcess(pname));
}
catch
{
return -1;
}
}

public static int GetMemoryUsageForProcess(uint pid)
{
int mem = 0;
int pHandle = OpenProcess(0x0400 | 0x0010, 0, pid);
PROCESS_MEMORY_COUNTERS pmc = new PROCESS_MEMORY_COUNTERS();
if(GetProcessMemoryInfo(pHandle, pmc, 40) != 0) mem = pmc.WorkingSetSize;
CloseHandle(pHandle);
return mem;
}

public static bool IsMoreThanOneRunning(string pname)
{
if(GetNumberRunning(pname) > 1) return true;
else return false;
}



public static void ExitSystem(EWX_ENUM exval)
{
TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();
TOKEN_PRIVILEGES tpOld = new TOKEN_PRIVILEGES();
LUID luid = new LUID();

LookupPrivilegeValue(null, "SeShutdownPrivilege",ref luid);
int processHandle = GetCurrentProcess();
int TokenHandle = 0;
OpenProcessToken(processHandle, 0x00000020 | 0x00000008, ref
TokenHandle);

tp.PriviledgeCount = 1;
tp.Attributes = 0x00000002;
tp.Luid = luid;

int tpsz = Marshal.SizeOf(tp);
tpsz = AdjustTokenPrivileges(TokenHandle, 0, ref tp, tpsz,0,0);
ExitWindowsEx((int)exval, 0);
}
}
}
 
Willy,

The WMI class does this? I assume it does not. The WMI classes might
provide an easier way to grant the SeShutdown privledge, but I would find it
hard to believe that it would just grant that permission to someone who does
not have it already.

In the case where you need to shut down remote machines, and there is no
trust relationship between those machines and the account you are currently
logged on as, then yes, I would say that using WMI is the better solution,
but for just shutting down the local machine (as the user that is running
the app), I feel the P/Invoke call is just fine.
 
Nicholas Paldino said:
Willy,

The WMI class does this? I assume it does not. The WMI classes might
provide an easier way to grant the SeShutdown privledge, but I would find
it hard to believe that it would just grant that permission to someone who
does not have it already.

In the case where you need to shut down remote machines, and there is
no trust relationship between those machines and the account you are
currently logged on as, then yes, I would say that using WMI is the better
solution, but for just shutting down the local machine (as the user that
is running the app), I feel the P/Invoke call is just fine.

Yes, WMI does this automatically, using System.Management you enable the
privilege by calling Scope.Options.EnablePrivileges = true.
Note that the caller must been granted the privilege to Shutdown (by default
all user have this), but being granted and being enabled are different
things when talking about privileges. Another great point using WMI is that
you don't need to know which privilege has to be enabled, it's included in
the mof file method description and automatically taken care of by WMI
Did you take a look at the amount of code you need to enable the privilege
using PInvoke?
Using PInvoke is only a valid option if the wanted functionality is not
offered through the FCL, which is IMO the whole point of .NET.

Willy.
 
Herbert VON GRÜNENWALD said:
Willy said:
In C#, it is still the same ExitWindowsEx API call.

class Class1
{
[DllImport("user32.dll")]
static extern bool ExitWindowsEx(uint uFlags, uint
dwReason);

[STAThread]
static void Main(string[] args)
{
ExitWindowsEx(1, 0); //this will cause the system
to
shut down.
}
}

uFlags
4 = Force any applications to quit instead of prompting the user to close
them.
0 = Log off the network.
8 = Shut down the system and, if possible, turn the computer off.
2 = Perform a full reboot of the system.
1 = Shut down the system.


message
in c++ it was ExitWindowsEx()

thanks

Did you test your code? If you actualy did you would have noticed that
this doesn't work.
The reason is simple, you have to enable the "SeShutdown" privilege using
PInvoke, something more complicated than calling ExitWindowsEx.

Willy.
yes, it dosn't work, the version that works is (a little bit more
longuer...):

using System;
using System.Runtime.InteropServices;


namespace WINAPIInterface
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class WINAPIProcess
{
public WINAPIProcess()
{
//
// TODO: Add constructor logic here
//
}
[StructLayout(LayoutKind.Sequential)]
public struct ProcessEntry32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)] public string
szExeFile;
};


[DllImport("KERNEL32.DLL")]
public static extern int CreateToolhelp32Snapshot(uint flags, uint
processid);

[DllImport("KERNEL32.DLL")]
public static extern int Process32First(int handle, ref ProcessEntry32
pe);

[DllImport("KERNEL32.DLL")]
public static extern int Process32Next(int handle, ref ProcessEntry32 pe);

[DllImport("KERNEL32.DLL")]
public static extern int CloseHandle(int handle);

public uint SNAPPROCESS = 2;

[DllImport("KERNEL32.DLL")]
public static extern int OpenProcess(uint dwDesiredAccess, int
bInheritHandle, uint dwProcessId);

[StructLayout(LayoutKind.Sequential)]
public class PROCESS_MEMORY_COUNTERS
{
public int cb;
public int PageFaultCount;
public int PeakWorkingSetSize;
public int WorkingSetSize;
public int QuotaPeakPagedPoolUsage;
public int QuotaPagedPoolUsage;
public int QuotaPeakNonPagedPoolUsage;
public int QuotaNonPagedPoolUsage;
public int PagefileUsage;
public int PeakPagefileUsage;
}

[DllImport("psapi.dll")]
public static extern int GetProcessMemoryInfo(int hProcess, [Out]
PROCESS_MEMORY_COUNTERS counters, int size);

[StructLayout(LayoutKind.Sequential)]
public struct LUID
{
public uint LowPart;
public uint HighPart;
};

public const int ANYSIZE_ARRAY = 1;

[StructLayout(LayoutKind.Sequential)]
public struct TOKEN_PRIVILEGES
{
public uint PriviledgeCount;
public LUID Luid;
public uint Attributes;

}

[DllImport("KERNEL32.DLL")]
public static extern int GetCurrentProcess();

[DllImport("advapi32.dll")]
public static extern System.Boolean OpenProcessToken(
int ProcessHandle,
uint DesiredAccess,
ref int Tokenhandle
);

[DllImport("advapi32.dll")]
public static extern System.Boolean LookupPrivilegeValue(
string lpSsytemName,
string lpName,
ref LUID pluid);

[DllImport("advapi32.dll")]
public static extern int AdjustTokenPrivileges(
int TokenHandle,
int DisableAllPrivileges,
[MarshalAs(UnmanagedType.Struct)]ref TOKEN_PRIVILEGES NewState,
int BufferLength,
int PreviousState,
int ReturnLength);

[DllImport("user32.dll")]
public static extern bool ExitWindowsEx(int flg, int rea);

public enum EWX_ENUM
{
EWX_LOGOFF = 0x00000000,
EWX_SHUTDOWN = 0x00000001,
EWX_REBOOT = 0x00000002,
EWX_FORCE = 0x00000004,
EWX_POWEROFF= 0x00000008,
EWX_FORCEIFHUNG = 0x00000010,
EWX_FORCEREBOOT = EWX_REBOOT | EWX_FORCE,
EWX_FORCEIFHUNGREBOOT = EWX_REBOOT | EWX_FORCEIFHUNG,
EWX_FORCESHUTDOWN = EWX_SHUTDOWN | EWX_FORCE,
EWX_FORCEIFHUNGSHUTDOWN = EWX_SHUTDOWN | EWX_FORCEIFHUNG,
EWX_FORCEPOWEROFF = EWX_POWEROFF | EWX_FORCE,
EWX_FORCEIFHUNGPOWEROFF = EWX_POWEROFF | EWX_FORCEIFHUNG,
EWX_FORCELOGOFF = EWX_LOGOFF | EWX_FORCE,
EWX_FORCEIFHUNGLOGOFF = EWX_LOGOFF | EWX_FORCEIFHUNG
}

/// <summary>
/// Takes a snap shot of processes running on the computer, and searches
for a
/// specified process name [name.exe].
/// </summary>
/// <param name="pname">Process name to be searched for.</param>
/// <returns>true if process found and false otherwise.</returns>
public static bool FindProcessByName(string pname)
{

int SnapShot = CreateToolhelp32Snapshot(0x00000002, 0);
ProcessEntry32 pe32 = new ProcessEntry32();
pe32.dwSize = 296;

while(Process32Next(SnapShot, ref pe32) != 0)
{

string xname = pe32.szExeFile.ToString();

if(pname.CompareTo(xname) == 0)
{
CloseHandle(SnapShot);
return true;
}
}
CloseHandle(SnapShot);
return false;
}

public static int GetNumberRunning(string pname)
{
int ProcCount = 0;
int SnapShot = CreateToolhelp32Snapshot(0x00000002, 0);
ProcessEntry32 pe32 = new ProcessEntry32();
pe32.dwSize = 296;
while(Process32Next(SnapShot, ref pe32) != 0)
{
string xname = pe32.szExeFile.ToString();
if(pname.CompareTo(xname) == 0)
{
ProcCount++;
}
}
CloseHandle(SnapShot);
return ProcCount;
}

public static uint GetProcessIdForProcess(string pname)
{
uint procid = 0;
int SnapShot = CreateToolhelp32Snapshot(0x00000002, 0);
ProcessEntry32 pe32 = new ProcessEntry32();
pe32.dwSize = 296;
while(Process32Next(SnapShot, ref pe32) != 0)
{
string xname = pe32.szExeFile.ToString();
if(pname.CompareTo(xname) == 0)
{
procid = pe32.th32ProcessID;
break;
}
}
CloseHandle(SnapShot);
return procid;
}

public static int GetMemoryUsageForProcess(string pname)
{
try
{
return GetMemoryUsageForProcess(GetProcessIdForProcess(pname));
}
catch
{
return -1;
}
}

public static int GetMemoryUsageForProcess(uint pid)
{
int mem = 0;
int pHandle = OpenProcess(0x0400 | 0x0010, 0, pid);
PROCESS_MEMORY_COUNTERS pmc = new PROCESS_MEMORY_COUNTERS();
if(GetProcessMemoryInfo(pHandle, pmc, 40) != 0) mem = pmc.WorkingSetSize;
CloseHandle(pHandle);
return mem;
}

public static bool IsMoreThanOneRunning(string pname)
{
if(GetNumberRunning(pname) > 1) return true;
else return false;
}



public static void ExitSystem(EWX_ENUM exval)
{
TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();
TOKEN_PRIVILEGES tpOld = new TOKEN_PRIVILEGES();
LUID luid = new LUID();

LookupPrivilegeValue(null, "SeShutdownPrivilege",ref luid);
int processHandle = GetCurrentProcess();
int TokenHandle = 0;
OpenProcessToken(processHandle, 0x00000020 | 0x00000008, ref TokenHandle);

tp.PriviledgeCount = 1;
tp.Attributes = 0x00000002;
tp.Luid = luid;

int tpsz = Marshal.SizeOf(tp);
tpsz = AdjustTokenPrivileges(TokenHandle, 0, ref tp, tpsz,0,0);
ExitWindowsEx((int)exval, 0);
}
}
}


This contains a whole bunch of code not related to the shutdown action.
The relevant part in ExitSystem could be refactored a bit:
A handle (TokenHandle ) should be defined as an IntPtr to be platform
independent.
Use the managed Process.GetCurrentProcess() instead of WIN32
GetCurrentProcess.
What happens if an API call fails? So, add at least some error checking.

Willy.
 
Willy said:
Lebesgue said:
In C#, it is still the same ExitWindowsEx API call.

class Class1
{
[DllImport("user32.dll")]
static extern bool ExitWindowsEx(uint uFlags, uint
dwReason);

[STAThread]
static void Main(string[] args)
{
ExitWindowsEx(1, 0); //this will cause the system
to
shut down.
}
}

uFlags
4 = Force any applications to quit instead of prompting the user to
close
them.
0 = Log off the network.
8 = Shut down the system and, if possible, turn the computer off.
2 = Perform a full reboot of the system.
1 = Shut down the system.


message

in c++ it was ExitWindowsEx()

thanks
thanks

so there is no C# class that encapsulates this API ?


Yes there is, you could use System.Management classes and the WMI class
Win32_OperatingSystem.

public static void Main() {
ManagementBaseObject outParams = null;
ManagementClass os = new ManagementClass("Win32_OperatingSystem");
os.Get();
os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
ManagementBaseObject inParams = os.GetMethodParameters("Win32Shutdown");
inParams["Flags"] = "1"; // System shutdown
inParams["Reserved"] = "0";
foreach (ManagementObject mo in os.GetInstances())
outParams = mo.InvokeMethod("Win32Shutdown",
inParams, null);

Willy.

i've got an exception, during the call of os.Get(): PrivilegeNotHeld

(i've got Administrator rigths)

****************************************
System.Management.ManagementException: Privilège non maintenu.
at
System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus
errorCode)
at System.Management.ManagementObject.InvokeMethod(String
methodName, ManagementBaseObject inParameters, InvokeMethodOptions options)
****************************************

i've inversed the lines:
****************************************
os.Get();
os.Scope.Options.EnablePrivileges = true; // enables required security to
os.Scope.Options.EnablePrivileges = true; // enables required security
os.Get();
****************************************


the exception doesn't raises during os.Get(), now but during the
InvokeMethod...

i've tried to add:
****************************************
foreach (ManagementObject mo in os.GetInstances())
{
mo.Scope.Options.EnablePrivileges = true;
outParams = mo.InvokeMethod("Win32Shutdown", inParams, null);
}
****************************************

but i've got the same result...

any ideas ?
 
Herbert VON GRÜNENWALD said:
Willy said:
Lebesgue wrote:

In C#, it is still the same ExitWindowsEx API call.

class Class1
{
[DllImport("user32.dll")]
static extern bool ExitWindowsEx(uint uFlags, uint
dwReason);

[STAThread]
static void Main(string[] args)
{
ExitWindowsEx(1, 0); //this will cause the
system to
shut down.
}
}

uFlags
4 = Force any applications to quit instead of prompting the user to
close
them.
0 = Log off the network.
8 = Shut down the system and, if possible, turn the computer off.
2 = Perform a full reboot of the system.
1 = Shut down the system.


message

in c++ it was ExitWindowsEx()

thanks



thanks

so there is no C# class that encapsulates this API ?


Yes there is, you could use System.Management classes and the WMI class
Win32_OperatingSystem.

public static void Main() {
ManagementBaseObject outParams = null;
ManagementClass os = new ManagementClass("Win32_OperatingSystem");
os.Get();
os.Scope.Options.EnablePrivileges = true; // enables required security
privilege.
ManagementBaseObject inParams =
os.GetMethodParameters("Win32Shutdown");
inParams["Flags"] = "1"; // System shutdown
inParams["Reserved"] = "0";
foreach (ManagementObject mo in os.GetInstances())
outParams = mo.InvokeMethod("Win32Shutdown",
inParams, null);

Willy.

i've got an exception, during the call of os.Get(): PrivilegeNotHeld

(i've got Administrator rigths)

****************************************
System.Management.ManagementException: Privilège non maintenu.
at
System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus
errorCode)
at System.Management.ManagementObject.InvokeMethod(String methodName,
ManagementBaseObject inParameters, InvokeMethodOptions options)
****************************************

i've inversed the lines:
****************************************
os.Get();
os.Scope.Options.EnablePrivileges = true; // enables required security to
os.Scope.Options.EnablePrivileges = true; // enables required security
os.Get();
****************************************


the exception doesn't raises during os.Get(), now but during the
InvokeMethod...

i've tried to add:
****************************************
foreach (ManagementObject mo in os.GetInstances())
{
mo.Scope.Options.EnablePrivileges = true;
outParams = mo.InvokeMethod("Win32Shutdown", inParams, null);
}
****************************************

but i've got the same result...

any ideas ?

This is an unfortunate bug introduced with the v1.1 framework SP1
(v1.1.4322.2032 )( didn't exist in v1.1 and is corrected in v2.0 beta). You
should check with PSS to see if there is a fix available.
There is a new version of the Wminet_utils.dll available (see KB article
Q887814) don't know if it includes a fix for this bug.

Willy.
 
Back
Top