-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathProgram.cs
More file actions
324 lines (276 loc) · 10.4 KB
/
Program.cs
File metadata and controls
324 lines (276 loc) · 10.4 KB
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.Win32.TaskScheduler;
namespace MyTrayApp
{
public partial class SysTrayApp : Form
{
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.Run(new SysTrayApp());
}
private readonly NotifyIcon trayIcon;
private readonly ContextMenuStrip trayMenu;
private const string appName = "WinToLinux";
private readonly List<string> uefi = [];
private readonly List<string> uuid = [];
private readonly List<ToolStripMenuItem> bootOptions = [];
private string bootSequence;
private string currentValue;
private int shift;
private readonly int bootOptionsTrayStartIndex;
private readonly ToolStripMenuItem startButton = new("Start with system");
private readonly ToolStripMenuItem rebootToButton = new("Reboot now to...");
[GeneratedRegex("^(\\{){0,1}[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}(\\}){0,1}$")]
private static partial Regex UUIDRegEx();
public SysTrayApp()
{
// Create a simple tray menu with only one item.
trayMenu = new ContextMenuStrip();
trayMenu.Items.Add("Settings").Enabled = false;
trayMenu.Items.Add(new ToolStripSeparator());
startButton.Checked = IsTaskEnabled();
startButton.Click += OnRegisterInStartup;
trayMenu.Items.Add(startButton);
trayMenu.Items.Add(new ToolStripSeparator());
trayMenu.Items.Add(rebootToButton);
trayMenu.Items.Add(new ToolStripSeparator());
bootOptionsTrayStartIndex = trayMenu.Items.Count;
RefreshMenuItems();
trayMenu.Items.Add(new ToolStripSeparator());
trayMenu.Items.Add("Reboot system", null, OnReboot);
trayMenu.Items.Add(new ToolStripSeparator());
trayMenu.Items.Add("Exit", null, OnExit);
// Create a tray icon.
trayIcon = new NotifyIcon
{
Text = "Reboot to Linux",
Icon = WinToLinux.Properties.Resources.WtL,
// Add menu to tray icon and show it.
ContextMenuStrip = trayMenu,
Visible = true
};
trayIcon.ContextMenuStrip.Opening += (_, _) =>
{
RefreshMenuItems();
};
}
private void OnExit(object sender, EventArgs e)
{
Application.Exit();
}
private void SetNextBoot(object sender, EventArgs _)
{
if (sender is not ToolStripMenuItem clickedItem || clickedItem.Tag is not string uuid)
return;
// Set the boot sequence
string args = $"/Set {{fwbootmgr}} BootSequence {uuid} /AddFirst";
var psi = new ProcessStartInfo
{
FileName = "bcdedit",
Arguments = args,
CreateNoWindow = true
};
Process.Start(psi);
Console.WriteLine("bcdedit" + args);
// Update the radio button selection
SetRadioButtonSelection(uuid);
// Update the current value
currentValue = uuid;
}
private void SetRadioButtonSelection(string selectedUUID)
{
// First, uncheck all boot option menu items
foreach (var item in bootOptions)
{
if (item.Tag is string itemUUID)
{
item.Checked = (itemUUID == selectedUUID);
}
}
}
private void RefreshMenuItems()
{
uuid.Clear();
uefi.Clear();
if (bootOptions.Count > 0)
{
bootOptions.ForEach(item => trayMenu.Items.Remove(item));
bootOptions.Clear();
rebootToButton.DropDownItems.Clear();
}
GetMenuItems();
currentValue = bootSequence ?? uuid.FirstOrDefault(string.Empty);
shift = uuid.Count - uefi.Count;
foreach (var (value, i) in uefi.Select((value, i) => (value, i)))
{
string itemTag = i + shift < uuid.Count ? uuid[i + shift] : string.Empty;
var bootItem = new ToolStripMenuItem
{
CheckOnClick = true,
Tag = itemTag,
Text = value
};
bootItem.Click += SetNextBoot;
bootOptions.Add(bootItem);
var immediateItem = new ToolStripMenuItem
{
Tag = itemTag,
Text = value
};
immediateItem.Click += (sender, _) =>
{
SetNextBoot(sender, _);
OnReboot(sender, _);
};
rebootToButton.DropDownItems.Add(immediateItem);
}
// Update radio button selection
SetRadioButtonSelection(currentValue);
for (int i = 0; i < bootOptions.Count; i++)
{
trayMenu.Items.Insert(bootOptionsTrayStartIndex + i, bootOptions[i]);
}
}
private static void CreateTask()
{
try
{
using var ts = new TaskService();
var td = ts.NewTask();
string currentUser = $"{Environment.UserDomainName}\\{Environment.UserName}";
td.RegistrationInfo.Description = "WinToLinux. Start on boot";
td.Triggers.Add(new LogonTrigger() { UserId = currentUser });
td.Actions.Add(new ExecAction(Application.ExecutablePath, null, null));
td.Principal.RunLevel = TaskRunLevel.Highest;
td.Settings.StopIfGoingOnBatteries = false;
td.Settings.DisallowStartIfOnBatteries = false;
td.Settings.UseUnifiedSchedulingEngine = true; // why not?
ts.RootFolder.RegisterTaskDefinition(appName, td);
}
catch (Exception ex)
{
MessageBox.Show($"Error creating startup task: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private static void DeleteTask()
{
using var ts = new TaskService();
if (ts.GetTask(appName) != null)
{
ts.RootFolder.DeleteTask(appName);
}
}
private static bool IsTaskEnabled()
{
using var ts = new TaskService();
return ts.GetTask(appName) != null;
}
private void OnRegisterInStartup(object _, EventArgs e)
{
if (IsTaskEnabled())
{
DeleteTask();
startButton.Checked = false;
}
else
{
CreateTask();
startButton.Checked = true;
}
}
private void OnReboot(object sender, EventArgs e)
{
var psi = new ProcessStartInfo("shutdown", "/r /t 0");
psi.CreateNoWindow = true;
Process.Start(psi);
}
private void GetMenuItems()
{
var psi = new ProcessStartInfo
{
FileName = "bcdedit",
Arguments = "/enum firmware",
RedirectStandardOutput = true,
CreateNoWindow = true,
UseShellExecute = false
};
using var process = new Process { StartInfo = psi };
process.OutputDataReceived += ParseBCDEditOutput;
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
}
void ParseBCDEditOutput(object sender, DataReceivedEventArgs e)
{
if (string.IsNullOrEmpty(e.Data))
return;
string strMessage = e.Data;
string[] splitMsg = strMessage.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (splitMsg.Length == 0)
return;
var match = UUIDRegEx().Match(splitMsg.Last());
if (splitMsg[0] == "description")
{
var description = string.Join(" ", splitMsg.Skip(1));
Console.WriteLine(description);
uefi.Add(description);
}
else if (splitMsg[0] == "bootsequence")
{
Console.Write(splitMsg.Last());
bootSequence = splitMsg.Last();
}
else if (splitMsg[0] != "resumeobject" && splitMsg[0] != "bootsequence" &&
(match.Success || splitMsg.Last() == "{bootmgr}"))
{
Console.Write(splitMsg.Last());
uuid.Add(splitMsg.Last());
}
}
// All below for hide a Form
protected override void OnLoad(EventArgs e)
{
Visible = false; // Hide form window.
ShowInTaskbar = false; // Remove from taskbar.
base.OnLoad(e);
}
protected override void Dispose(bool isDisposing)
{
if (isDisposing)
{
// Release the icon resource.
trayIcon.Dispose();
trayMenu?.Dispose();
}
base.Dispose(isDisposing);
}
}
public class ContextMenuStrip : System.Windows.Forms.ContextMenuStrip
{
private new void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew)
{
// Use reflection to invoke the internal ResetScaling method
var resetScalingMethod = typeof(System.Windows.Forms.ContextMenuStrip).GetMethod("ResetScaling", BindingFlags.NonPublic | BindingFlags.Instance);
resetScalingMethod?.Invoke(this, [deviceDpiNew]);
}
public ContextMenuStrip(IContainer container) : base(container)
{
RescaleConstantsForDpi(96, DeviceDpi);
}
public ContextMenuStrip()
{
RescaleConstantsForDpi(96, DeviceDpi);
}
}
}