C#のシャットダウンについてご紹介!ログオフや再起動をする

- システム
エンジニア - C#でのシャットダウやログオフの方法を教えてください。
- プロジェクト
マネージャー - ここではWMIを利用したシャットダウンの方法を見ていきましょう。
C#のシャットダウンについて
今回は、C#のシャットダウンについて説明します。
C#のアプリケーションから、システムをシャットダウンしたり再起動したりでき、C#のシャットダウンに興味のある方はぜひご覧ください。
ここで紹介すること
ここでは、C#のシャットダウンの方法を2種類紹介します。
・WMIでシャットダウンする
WMIのWin32_OperatingSystemクラスを利用して、ログオフ、シャットダウン、再起動、電源OFFができます。
Win32Shutdownメソッドで上記の操作ができます。
・shutdown.exeでシャットダウンする
shutdown.exeを使用することで、より簡単にシャットダウンできます。
shutdown.exeの引数を指定することで、ログオフ、シャットダウン、再起動ができます。
また、シャットダウンのイベントを検知できますので、検知方法についても紹介します。
WMIでシャットダウンする
C#では、WMIのWin32_OperatingSystemクラスを利用して、ログオフ、シャットダウン、再起動、電源OFFができます。また、強制的に上記の操作を行うこともできます。
実際のソースコードを見てみましょう。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
|
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Management;
using System.Threading;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
ComboBox comboBox;
Button button;
CheckBox checkBox;
Label label;
public Form1()
{
// コンボボックス
comboBox = new ComboBox();
comboBox.Location = new Point(20, 20);
comboBox.Items.AddRange(new string[] { "Logoff", "Shutdown", "Reboot", "PowerOff" });
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
// ラベル
label = new Label();
label.Location = new Point(35, 50);
label.Text = "Forced";
// チェックボックス
checkBox = new CheckBox();
checkBox.Location = new Point(20, 50);
checkBox.AutoSize = true;
// ボタン
button = new Button();
button.Location = new Point(20, 75);
button.Text = "Execute";
button.Click += Button_Click;
this.Controls.Add(comboBox);
this.Controls.Add(label);
this.Controls.Add(checkBox);
this.Controls.Add(button);
this.Text = "Form1";
this.Load += new EventHandler(Form1_Load);
}
private void Button_Click(object sender, EventArgs e)
{
ShutdownFlags shutdownFlags;
switch (comboBox.Text)
{
case "Logoff":
shutdownFlags = ShutdownFlags.Logoff;
break;
case "Shutdown":
shutdownFlags = ShutdownFlags.Shutdown;
break;
case "Reboot":
shutdownFlags = ShutdownFlags.Reboot;
break;
case "PowerOff":
shutdownFlags = ShutdownFlags.PowerOff;
break;
default:
throw new Exception("Unknown Shutdown Flag");
}
int flags = (int)shutdownFlags;
if (checkBox.Checked)
{
// 強制的に実行するフラグ
flags += (int)ShutdownFlags.Forced;
}
Console.WriteLine(flags);
// ユーザー特権を有効にするための設定
ConnectionOptions co = new ConnectionOptions();
co.Impersonation = ImpersonationLevel.Impersonate;
co.EnablePrivileges = true;
// ManagementScopeを作成
ManagementScope sc = new ManagementScope("\\ROOT\\CIMV2", co);
// 接続
sc.Connect();
ObjectQuery oq = new ObjectQuery("select * from Win32_OperatingSystem");
ManagementObjectSearcher mos = new ManagementObjectSearcher(sc, oq);
// Shutdownメソッドを呼び出す
foreach (ManagementObject mo in mos.Get())
{
// Win32Shutdownメソッドを呼び出す
mo.InvokeMethod(
// 実行メソッド名
"Win32Shutdown",
// メソッドの引数指定
new object[] { flags, 0 }
);
mo.Dispose();
}
mos.Dispose();
}
private void Form1_Load(object sender, EventArgs e)
{
// 初期値(未選択状態)
comboBox.SelectedIndex = 0;
}
}
// シャットダウンフラグ
enum ShutdownFlags
{
// ログオフ(サインアウト)
Logoff = 0,
// シャットダウン
Shutdown = 1,
// 再起動
Reboot = 2,
// 電源オフ
PowerOff = 8,
// 強制的に実行
Forced = 4
}
}
|
プルダウンで操作を選択し、”Execute”ボタンをクリックすると、目的の操作が行えます。
このように、C#ではWMIのWin32_OperatingSystemクラスを利用して、ログオフ、シャットダウン、再起動、電源OFFができます。
shutdown.exeでシャットダウンする
C#では、shutdown.exeを使用してログオフ、シャットダウン、再起動できます。また、強制的に上記の操作を行うこともできます。
実際のソースコードを見てみましょう。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
ComboBox comboBox;
Button button;
CheckBox checkBox;
Label label;
public Form1()
{
// コンボボックス
comboBox = new ComboBox();
comboBox.Location = new Point(20, 20);
comboBox.Items.AddRange(new string[] { "Logoff", "Shutdown", "Reboot" });
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
// ラベル
label = new Label();
label.Location = new Point(35, 50);
label.Text = "Forced";
// チェックボックス
checkBox = new CheckBox();
checkBox.Location = new Point(20, 50);
checkBox.AutoSize = true;
// ボタン
button = new Button();
button.Location = new Point(20, 75);
button.Text = "Execute";
button.Click += Button_Click;
this.Controls.Add(comboBox);
this.Controls.Add(label);
this.Controls.Add(checkBox);
this.Controls.Add(button);
this.Text = "Form1";
this.Load += new EventHandler(Form1_Load);
}
private void Button_Click(object sender, EventArgs e)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "shutdown.exe";
switch (comboBox.Text)
{
case "Logoff":
psi.Arguments = "/l";
break;
case "Shutdown":
psi.Arguments = "/s";
break;
case "Reboot":
psi.Arguments = "/r";
break;
default:
throw new Exception("Unknown Shutdown Flag");
}
if (checkBox.Checked)
{
// 強制的に実行
psi.Arguments += " /f";
}
Console.WriteLine(psi.Arguments);
//ウィンドウを表示しないようにする
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
//起動
Process.Start(psi);
}
private void Form1_Load(object sender, EventArgs e)
{
// 初期値(未選択状態)
comboBox.SelectedIndex = 0;
}
}
}
|
プルダウンで操作を選択し、”Execute”ボタンをクリックすると、目的の操作が行えます。
このように、C#ではshutdown.exeを使用してシャットダウンできます。
シャットダウンの検知
C#では、シャットダウンやログオフの発生イベントを検知できます。
実際のソースコードを見てみましょう。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
using System;
using System.Windows.Forms;
using Microsoft.Win32;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
this.Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
SystemEvents.SessionEnding += SystemEvents_SessionEnding;
}
private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
if (e.Reason == SessionEndReasons.Logoff)
{
MessageBox.Show("ログオフを検知しました");
}
else if (e.Reason == SessionEndReasons.SystemShutdown)
{
MessageBox.Show("シャットダウンを検知しました");
}
}
}
}
|
Windowsメニューから、ログオフやシャットダウンしてみてください。
SystemEvents.SessionEndingのイベントハンドラで、イベントを検知してメッセージを表示します。
このように、C#ではシャットダウンやログオフの発生イベントを検知できます。
- システム
エンジニア - 再起動や電源オフまでできるなんて、便利ですね。
- プロジェクト
マネージャー - WMIの他にshutdown.exeを利用した方法の2つを紹介しました。いかがでしたか?
C#のシャットダウン方法を正しく理解して使用しましょう。
いかがでしたでしょうか。C#でWMIでシャットダウンする方法およびshutdown.exeでシャットダウンする方法を紹介しました。
シャットダウンだけでなく、ログオフや再起動もでき、シャットダウンなどのイベントを検知できます。ぜひご自身でソースコードを書いて、理解を深めてください。
FEnet.NETナビ・.NETコラムは株式会社オープンアップシステムが運営しています。
株式会社オープンアップシステムはこんな会社です
秋葉原オフィスには株式会社オープンアップシステムをはじめグループのIT企業が集結!
数多くのエンジニアが集まります。

-
スマホアプリから業務系システムまで
スマホアプリから業務系システムまで開発案件多数。システムエンジニア・プログラマーとしての多彩なキャリアパスがあります。
-
充実した研修制度
毎年、IT技術のトレンドや社員の要望に合わせて、カリキュラムを刷新し展開しています。社内講師の丁寧なサポートを受けながら、自分のペースで学ぶことができます。
-
資格取得を応援
スキルアップしたい社員を応援するために資格取得一時金制度を設けています。受験料(実費)と合わせて資格レベルに合わせた最大10万円の一時金も支給しています。
-
東証プライム上場企業グループ
オープンアップシステムは東証プライム上場「株式会社オープンアップグループ」のグループ企業です。
安定した経営基盤とグループ間のスムーズな連携でコロナ禍でも安定した雇用を実現させています。
株式会社オープンアップシステムに興味を持った方へ
株式会社オープンアップシステムでは、開発系エンジニア・プログラマを募集しています。
年収をアップしたい!スキルアップしたい!大手の上流案件にチャレンジしたい!
まずは話だけでも聞いてみたい場合もOK。お気軽にご登録ください。


C#新着案件New Job
-
システム開発/東京都新宿区/【WEB面談可/C#経験者/20代前半の方活躍中/経験1年以上の方活躍中】/在宅勤務
月給29万~34万円東京都新宿区(新宿駅) -
システム開発/東京都新宿区/【WEB面談可/C#経験者/20代後半~40代の方活躍中/経験年数不問】/在宅勤務
月給41万~50万円東京都新宿区(新宿駅) -
デバック、テスト項目の作成/神奈川県横浜市/【WEB面談可/C#経験者/20代前半の方活躍中/経験1年以上の方活躍中】/在宅勤務
月給29万~34万円神奈川県横浜市(桜木町駅) -
デバック、テスト項目の作成/神奈川県横浜市/【WEB面談可/C#経験者/20代後半~40代の方活躍中/経験年数不問】/在宅勤務
月給41万~50万円神奈川県横浜市(桜木町駅) -
基幹システム開発導入/東京都新宿区/【WEB面談可/C#経験者/20代前半の方活躍中/経験1年以上の方活躍中】/在宅勤務
月給29万~34万円東京都新宿区(西新宿駅) -
基幹システム開発導入/東京都新宿区/【WEB面談可/C#経験者/20代後半~40代の方活躍中/経験年数不問】/在宅勤務
月給41万~50万円東京都新宿区(西新宿駅)