C# を使用してコンピューターをシャットダウンするには?
7 に答える
簡単な方法: Process.Start を使用して shutdown.exe を実行します。
shutdown /s /t 0
プログラムによる方法: P/Invoke a call to ExitWindowsEx
これは P/Invoke 署名になります。
[DllImport("aygshell.dll", SetLastError="true")]
private static extern bool ExitWindowsEx(uint dwFlags, uint dwReserved);
どのような状況でも、コードを実行しているユーザーはシステム権限をシャットダウンする必要があります (通常は問題ありませんが、覚えておくべき重要な点です)。
さまざまな方法:
A. System.Diagnostics.Process.Start("Shutdown", "-s -t 10");
B. Windows Management Instrumentation (WMI)
http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=36953
http://www.dreamincode.net/forums/showtopic33948.htm
C. System.Runtime.InteropServices Pinvoke
http://bytes.com/groups/net-c/251367-shutdown-my-computer-using-c
D. システム管理
http://www.geekpedia.com/code36_Shut-down-system-using-Csharp.html
私が送信した後、他の多くの人が投稿しているのを見ました...
WindowsControllerは、ExitWindowsEx の ac# ラッパー クラスです。
場合によっては、アプリケーションからオペレーティング システムを再起動またはシャットダウンする必要があります (たとえば、プログラムのインストール後)。.NET フレームワークは、System.Management 名前空間の Windows Management Instrumentation (WMI) クラスを介してコンピューターを間接的に再起動する方法を提供しますが、その実装にはいくつかの問題があるようです。
そのため、Windows を再起動およびシャットダウンする API 関数を実装する WindowsController クラスを作成しました。すべての ExitWindowsEx モードをサポートし、システムを休止状態にしてサスペンドすることもできます。
このクラスは、C# および VB.NET バージョンで使用できます。.NET モジュールまたはライブラリにコンパイルして、他の .NET 言語から使用できます。Windows API に依存しているため、Linux や FreeBSD では動作しません。
(mentalis.org)
ここに示す「ユーザー ログオフ」コードのバリエーションを使用します。
そのコードはExitWindowsExAPI 呼び出しを使用します。
推測では(未テスト):
Process.Start("shutdown", "-s -t 0");
難しい方法は、ラップトップで完全に機能しますが、時間がかかります。
Spawn a couple endless loops in more threads than cpu cores.
Wait for overheat which will automatically shutdown a computer.
:)
InitiateSystemShutdown を使用することもできます
http://www.pinvoke.net/default.aspx/advapi32.initiatesystemshutdown
using System;
using System.Runtime.InteropServices;
using System.Text;
public class Program
{
[DllImport( "advapi32.dll" ) ]
public static extern bool InitiateSystemShutdown( string MachineName , string Message , uint Timeout , bool AppsClosed , bool Restart );
[DllImport( "kernel32.dll" ) ]
public static extern uint GetLastError();
[DllImport( "kernel32.dll" ) ]
public static extern uint FormatMessage( uint Flags , IntPtr Source , uint MessageID , uint LanguageID , StringBuilder Buffer , uint Size , IntPtr Args );
public static void Main()
{
InitiateSystemShutdown(System.Environment.MachineName, "hello", 0, false, false);
//InitiateSystemShutdown("localhost", "hello", 0, false, false);
}
}