How to shut down with C #, Process.Start ("shutdown") not working in Windows XP

After some of you discuss how to reset my computer and or turn it off from C #, I found this explanation on how to do it:

ManagementBaseObject outParameters = null;
ManagementClass sysOS = new ManagementClass("Win32_OperatingSystem");
sysOS.Get();

// Enables required security privilege.
sysOS.Scope.Options.EnablePrivileges = true;

// Get our in parameters
ManagementBaseObject inParameters = sysOS.GetMethodParameters("Win32Shutdown");

// Pass the flag of 0 = System Shutdown
inParameters["Flags"] = "1"; //shut down.
inParameters["Reserved"] = "0";
foreach (ManagementObject manObj in sysOS.GetInstances())
{
    outParameters = manObj.InvokeMethod("Win32Shutdown", inParameters, null);
}

This worked on Windows 7, but not on a Windows XP window, I tried it. Therefore, I realized that it allows me to switch to a simpler solution:

Process.Start("shutdown", "/s /t 00");

, , , Windows 7, Windows XP box. Windows XP, , , , , , ... - , , ( , sys X, ...) ? FormClosing:

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (!canExit)
    {
        e.Cancel = true;
        this.WindowState = FormWindowState.Minimized;
    }
    else
    {
        // Write out the logs.
        List<String> logs = LogUtil.getLog(); // mic.getLog();

        // Create a writer and open the file
        TextWriter tw = new StreamWriter(userAppData + "\\logTMC.txt", true);

        // Write a line of text to the file
        tw.WriteLine("----- " + DateTime.Now + " ------");
        foreach (String log in logs)
        {
            tw.WriteLine(log);
        }

        // Close the stream
        tw.Close();
    }
}

, reset, # Windows 7, Windows XP... , - ? ? , , ? - reset, , Windows XP, , SVN Windows, , .

, , . Process.Start() , , " " ?

+3
3

API ExitWindowsEx pinvoke.net.

ExitWindowsEx, ExitWindows-Enum ShutdownReason-Enum pinvoke.net . , SE_SHUTDOWN_NAME (, AdjustTokenPrivileges API).

"" ( - , , YMMV).

, , Process.Start(), , shutdown.exe . - EXE- PATH. , , , "real" shutdown.exe, . - Process.Start(Environment.ExpandEnvironmentVariables("%windir%\system32\shutdown.exe")), , shutdown.exe ( , ).

+3

, .

, : #

, , XP, Pop Catalin Process.Start("shutdown","/s /t 0");. , 1 0 .

+1

I believe that is correct. You just need to change the command:

shutdown.exe -s -t 00

It works on my windows box (from cmd).

0
source

Source: https://habr.com/ru/post/1765036/


All Articles