-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
286 lines (233 loc) · 9.9 KB
/
Copy pathProgram.cs
File metadata and controls
286 lines (233 loc) · 9.9 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
using System.Runtime.InteropServices;
using System.Management.Automation;
using System.Security.Principal;
using Microsoft.Win32.TaskScheduler;
namespace XPSThermalTray;
class RoundedContextMenuStrip : ContextMenuStrip
{
[DllImport("dwmapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern long DwmSetWindowAttribute(IntPtr hwnd,
DWMWINDOWATTRIBUTE attribute,
ref DWM_WINDOW_CORNER_PREFERENCE pvAttribute,
uint cbAttribute);
public RoundedContextMenuStrip()
{
var preference = DWM_WINDOW_CORNER_PREFERENCE.DWMWCP_ROUND; //change as you want
DwmSetWindowAttribute(Handle,
DWMWINDOWATTRIBUTE.DWMWA_WINDOW_CORNER_PREFERENCE,
ref preference,
sizeof(uint));
}
public enum DWMWINDOWATTRIBUTE
{
DWMWA_WINDOW_CORNER_PREFERENCE = 33
}
public enum DWM_WINDOW_CORNER_PREFERENCE
{
DWMWA_DEFAULT = 0,
DWMWCP_DONOTROUND = 1,
DWMWCP_ROUND = 2,
DWMWCP_ROUNDSMALL = 3,
}
}
public enum ThermalProfile
{
UltraPerformance,
Quiet,
Cool,
Optimized
}
static class Program
{
static NotifyIcon notifyIcon = null!;
static ContextMenuStrip contextMenu = null!;
private static readonly Dictionary<ThermalProfile, int> profileToIndexMap = new Dictionary<ThermalProfile, int>
{
{ ThermalProfile.Cool, 3 },
{ ThermalProfile.Optimized, 4 },
{ ThermalProfile.Quiet, 5 },
{ ThermalProfile.UltraPerformance, 6 },
};
private static readonly Dictionary<int, ThermalProfile> indexToProfileMap = profileToIndexMap.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
private static string appPath = Application.ExecutablePath;
private static string assetsPath = Path.Combine(Application.StartupPath, "assets");
private static Image loadingImg = Image.FromFile(Path.Combine(assetsPath, "loading.gif"));
private static Image checkImg = Image.FromFile(Path.Combine(assetsPath, "check.png"));
const string appName = "Dell XPS Thermal Tray";
[STAThread]
static void Main()
{
AppDomain? currentDomain = default(AppDomain);
currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += GlobalUnhandledExceptionHandler;
System.Windows.Forms.Application.ThreadException += GlobalThreadExceptionHandler;
ApplicationConfiguration.Initialize();
notifyIcon = new NotifyIcon();
notifyIcon.Icon = new Icon(Path.Combine(assetsPath, "fire.ico"));
notifyIcon.Text = appName;
contextMenu = new RoundedContextMenuStrip();
Font headerFont = new Font("Segoe UI", 10f, FontStyle.Bold);
contextMenu.Items.Add(" " + appName).Font = headerFont;
ToolStripMenuItem startupLaunchMi = new ToolStripMenuItem(" Start On Launch", null, OnStartOnLaunchClicked);
using (TaskService ts = new TaskService())
{
var existingTask = ts.GetTask(appName);
startupLaunchMi.Image = existingTask != null && existingTask.Enabled ? checkImg : null;
}
contextMenu.Items.Add(startupLaunchMi);
contextMenu.Items.Add(new ToolStripSeparator());
contextMenu.Items.Add(" ❄️ Cool", loadingImg, OnMenuItemClicked);
contextMenu.Items.Add(" 📈 Optimized", loadingImg, OnMenuItemClicked);
contextMenu.Items.Add(" 🔇 Quiet", loadingImg, OnMenuItemClicked);
contextMenu.Items.Add(" 🔥 Ultra Performance", loadingImg, OnMenuItemClicked);
contextMenu.Items.Add(new ToolStripSeparator());
contextMenu.Items.Add(" Quit", null, (_, _) => Environment.Exit(0));
contextMenu.Closing += ContextMenuStrip_Closing;
notifyIcon.ContextMenuStrip = contextMenu;
notifyIcon.Visible = true;
var hasAdminAccess = IsAdministrationRules();
Console.WriteLine("Has admin access: " + hasAdminAccess);
if (!hasAdminAccess)
{
MessageBox.Show("Admin access is required. Closing...");
Environment.Exit(0);
}
updateCurrentProfile();
periodicUpdate();
Application.Run();
}
private static async void periodicUpdate()
{
var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
while (await timer.WaitForNextTickAsync())
{
updateCurrentProfile();
}
}
private static bool IsAdministrationRules()
{
try
{
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
return (new WindowsPrincipal(identity)).IsInRole(WindowsBuiltInRole.Administrator);
}
}
catch
{
return false;
}
}
private static async void updateCurrentProfile()
{
var currentProfile = await getCurrentThermalProfileAsync();
clearContextMenuImages();
(contextMenu.Items[profileToIndexMap[currentProfile]] as ToolStripMenuItem)!.Image = checkImg;
}
private static void clearContextMenuImages()
{
for (int i = 3; i < 7; i++)
{
ToolStripMenuItem menuItem = (contextMenu.Items[i] as ToolStripMenuItem)!;
menuItem.Image = null;
}
}
private static async Task<ThermalProfile> getCurrentThermalProfileAsync()
{
using (PowerShell ps = PowerShell.Create())
{
await ps.AddCommand("Set-ExecutionPolicy")
.AddParameter("ExecutionPolicy", "RemoteSigned")
.AddParameter("Scope", "Process")
.InvokeAsync();
ps.Commands.Clear();
await ps.AddCommand("Import-Module").AddParameter("Name", "DellBIOSProvider").InvokeAsync();
ps.Commands.Clear();
await ps.AddCommand("cd").AddArgument("dellsmbios:").InvokeAsync();
ps.Commands.Clear();
var result = await ps.AddCommand("Get-Item").AddArgument(@".\PreEnabled\ThermalManagement").AddCommand("Select-Object").AddParameter("Property", "CurrentValue").InvokeAsync();
var resultString = (result[0].Properties["CurrentValue"].Value as string)!;
if (Enum.TryParse<ThermalProfile>(resultString, out var profile))
{
return profile;
}
else
{
throw new Exception("Invalid Thermal Profile");
}
}
}
private static async void setCurrentThermalProfile(ThermalProfile profile)
{
using (PowerShell ps = PowerShell.Create())
{
await ps.AddCommand("Set-ExecutionPolicy")
.AddParameter("ExecutionPolicy", "RemoteSigned")
.AddParameter("Scope", "Process")
.InvokeAsync();
ps.Commands.Clear();
await ps.AddCommand("Import-Module").AddParameter("Name", "DellBIOSProvider").InvokeAsync();
ps.Commands.Clear();
await ps.AddCommand("cd").AddArgument("dellsmbios:").InvokeAsync();
ps.Commands.Clear();
await ps.AddCommand("Set-Item").AddArgument(@".\PreEnabled\ThermalManagement").AddArgument(profile.ToString()).InvokeAsync();
clearContextMenuImages();
(contextMenu.Items[profileToIndexMap[profile]] as ToolStripMenuItem)!.Image = checkImg;
}
}
private static void OnStartOnLaunchClicked(object? sender, EventArgs e)
{
ToolStripMenuItem clickedMenuItem = (sender as ToolStripMenuItem)!;
clickedMenuItem.Image = clickedMenuItem.Image == checkImg ? null : checkImg;
using (TaskService ts = new TaskService())
{
var existingTask = ts.GetTask(appName);
if (existingTask != null && clickedMenuItem.Image != checkImg)
{
ts.RootFolder.DeleteTask(appName);
return;
}
if (clickedMenuItem.Image == checkImg && existingTask == null)
{
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = $"Launch {appName} at startup.";
td.Principal.RunLevel = TaskRunLevel.Highest;
td.Triggers.Add(new LogonTrigger { UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name });
td.Actions.Add(new ExecAction(appPath));
ts.RootFolder.RegisterTaskDefinition(appName, td);
}
}
}
private static void OnMenuItemClicked(object? sender, EventArgs e)
{
ToolStripMenuItem clickedMenuItem = (sender as ToolStripMenuItem)!;
if (clickedMenuItem.Image != checkImg)
{
clickedMenuItem.Image = loadingImg;
var index = contextMenu.Items.IndexOf(clickedMenuItem);
var profile = indexToProfileMap[index];
setCurrentThermalProfile(profile);
}
}
private static void ContextMenuStrip_Closing(object? sender, ToolStripDropDownClosingEventArgs e)
{
if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked)
{
e.Cancel = true;
}
}
private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Exception? ex = default(Exception);
ex = (Exception)e.ExceptionObject;
string crashLog = $"[Unhandled Exception] {DateTime.Now}\n\n{ex.ToString()}\n\n";
File.AppendAllText(Path.Combine(assetsPath, "crash.log"), crashLog);
}
private static void GlobalThreadExceptionHandler(object sender, System.Threading.ThreadExceptionEventArgs e)
{
Exception? ex = default(Exception);
ex = e.Exception;
string crashLog = $"[Thread Exception] {DateTime.Now}\n\n{ex.ToString()}\n\n";
File.AppendAllText(Path.Combine(assetsPath, "crash.log"), crashLog);
}
}