microsoft/TypeAgent

Public

mirrored from https://github.com/microsoft/TypeAgentAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
96de8d07300f81e972c9bc83ecbb39239f542a57

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

dotnet/autoShell/AutoShell.cs

1772lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4using System;
5using System.Collections;
6using System.Collections.Generic;
7using System.Diagnostics;
8using System.IO;
9using System.IO.Packaging;
10using System.Linq;
11using System.Reflection;
12using System.Runtime.InteropServices;
13using System.Text;
14using System.Threading.Tasks;
15using System.Windows.Controls;
16using Microsoft.VisualBasic;
17using Microsoft.VisualBasic.ApplicationServices;
18using Microsoft.WindowsAPICodePack.Shell;
19using Newtonsoft.Json;
20using Newtonsoft.Json.Linq;
21using static autoShell.AutoShell;
22
23
24namespace autoShell;
25
26internal partial class AutoShell
27{
28 // create a map of friendly names to executable paths
29 static Hashtable s_friendlyNameToPath = [];
30 static Hashtable s_friendlyNameToId = [];
31 static double s_savedVolumePct = 0.0;
32 static SortedList<string, string[]> s_sortedList;
33
34 static IServiceProvider10 s_shell;
35 static IVirtualDesktopManager s_virtualDesktopManager;
36 static IVirtualDesktopManagerInternal s_virtualDesktopManagerInternal;
37 static IVirtualDesktopManagerInternal_BUGBUG s_virtualDesktopManagerInternal_BUGBUG;
38 static IApplicationViewCollection s_applicationViewCollection;
39 static IVirtualDesktopPinnedApps s_virtualDesktopPinnedApps;
40
41
42 /// <summary>
43 /// Constructor used to get system wide information required for specific commands.
44 /// </summary>
45 static AutoShell()
46 {
47 // get current user name
48 string userName = Environment.UserName;
49 // known appication, path to executable, any env var for working directory
50 s_sortedList = new SortedList<string, string[]>
51 {
52 { "chrome", new[] { "chrome.exe" } },
53 { "power point", new[] { "C:\\Program Files\\Microsoft Office\\root\\Office16\\POWERPNT.EXE" } },
54 { "powerpoint", new[] { "C:\\Program Files\\Microsoft Office\\root\\Office16\\POWERPNT.EXE" } },
55 { "word", new[] { "C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE" } },
56 { "winword", new[] { "C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE" } },
57 { "excel", new[] { "C:\\Program Files\\Microsoft Office\\root\\Office16\\EXCEL.EXE" } },
58 { "outlook", new[] { "C:\\Program Files\\Microsoft Office\\root\\Office16\\OUTLOOK.EXE" } },
59 { "visual studio", new[] { "devenv.exe" } },
60 { "visual studio code", new[] { "C:\\Users\\" + userName + "\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe" } },
61 { "edge", new[] { "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" } },
62 { "microsoft edge", new[] { "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" } },
63 { "notepad", new[] { "C:\\Windows\\System32\\notepad.exe" } },
64 { "paint", new[] { "mspaint.exe" } },
65 { "calculator", new[] { "calc.exe" } },
66 { "file explorer", new[] { "C:\\Windows\\explorer.exe" } },
67 { "control panel", new[] { "C:\\Windows\\System32\\control.exe" } },
68 { "task manager", new[] { "C:\\Windows\\System32\\Taskmgr.exe" } },
69 { "cmd", new[] { "C:\\Windows\\System32\\cmd.exe" } },
70 { "powershell", new[] { "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" } },
71 { "snipping tool", new[] { "C:\\Windows\\System32\\SnippingTool.exe" } },
72 { "magnifier", new[] { "C:\\Windows\\System32\\Magnify.exe" } },
73 { "paint 3d", new[] { "C:\\Program Files\\WindowsApps\\Microsoft.MSPaint_10.1807.18022.0_x64__8wekyb3d8bbwe\\" } },
74 { "m365 copilot", new[] { "C:\\Program Files\\WindowsApps\\Microsoft.MicrosoftOfficeHub_19.2512.45041.0_x64__8wekyb3d8bbwe\\M365Copilot.exe" } },
75 { "copilot", new[] { "C:\\Program Files\\WindowsApps\\Microsoft.MicrosoftOfficeHub_19.2512.45041.0_x64__8wekyb3d8bbwe\\M365Copilot.exe" } },
76 { "spotify", new[] { "C:\\Program Files\\WindowsApps\\SpotifyAB.SpotifyMusic_1.278.418.0_x64__zpdnekdrzrea0\\spotify.exe" } },
77 { "github copilot", new[] { $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\\AppData\\Local\\Microsoft\\WinGet\\Packages\\GitHub.Copilot_Microsoft.Winget.Source_8wekyb3d8bbwe\\copilot.exe", "GITHUB_COPILOT_ROOT_DIR", "--allow-all-tools" } },
78 };
79
80 // add the entries to the hashtable
81 foreach (var kvp in s_sortedList)
82 {
83 s_friendlyNameToPath.Add(kvp.Key, kvp.Value[0]);
84 }
85
86 var installedApps = GetAllInstalledAppsIds();
87 foreach (var kvp in installedApps)
88 {
89 s_friendlyNameToId.Add(kvp.Key, kvp.Value);
90 }
91
92 // Load the installed themes
93 LoadThemes();
94
95 // Desktop management
96 s_shell = (IServiceProvider10)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_ImmersiveShell));
97 s_virtualDesktopManagerInternal = (IVirtualDesktopManagerInternal)s_shell.QueryService(CLSID_VirtualDesktopManagerInternal, typeof(IVirtualDesktopManagerInternal).GUID);
98 s_virtualDesktopManagerInternal_BUGBUG = (IVirtualDesktopManagerInternal_BUGBUG)s_shell.QueryService(CLSID_VirtualDesktopManagerInternal, typeof(IVirtualDesktopManagerInternal).GUID);
99 s_virtualDesktopManager = (IVirtualDesktopManager)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_VirtualDesktopManager));
100 s_applicationViewCollection = (IApplicationViewCollection)s_shell.QueryService(typeof(IApplicationViewCollection).GUID, typeof(IApplicationViewCollection).GUID);
101 s_virtualDesktopPinnedApps = (IVirtualDesktopPinnedApps)s_shell.QueryService(CLSID_VirtualDesktopPinnedApps, typeof(IVirtualDesktopPinnedApps).GUID);
102 }
103
104 /// <summary>
105 /// Program entry point
106 /// </summary>
107 /// <param name="args">Any command line arguments</param>
108 static void Main(string[] args)
109 {
110 string rawCmdLine = Marshal.PtrToStringUni(GetCommandLineW());
111
112 // if there are command line args let's execute those one at a time and then exit
113 // user can specify a single JSON object command or an array of them on the command line
114 if (args.Length > 0)
115 {
116 string exe = $"\"{Environment.ProcessPath}\"";
117 string cmdLine = rawCmdLine.Replace(exe, "");
118
119 if (cmdLine.StartsWith(exe, StringComparison.OrdinalIgnoreCase))
120 {
121 cmdLine = cmdLine[exe.Length..];
122 }
123 else if (cmdLine.StartsWith(Path.GetFileName(Environment.ProcessPath), StringComparison.OrdinalIgnoreCase))
124 {
125 cmdLine = cmdLine[Path.GetFileName(Environment.ProcessPath).Length..];
126 }
127 else if (cmdLine.StartsWith(Path.GetFileNameWithoutExtension(Environment.ProcessPath), StringComparison.OrdinalIgnoreCase))
128 {
129 cmdLine = cmdLine[Path.GetFileNameWithoutExtension(Environment.ProcessPath).Length..];
130 }
131
132 try
133 {
134 JArray commands = JArray.Parse(cmdLine);
135 foreach (JObject jo in commands.Children<JObject>())
136 {
137 execLine(jo);
138 }
139 }
140 catch (JsonReaderException)
141 {
142 execLine(JObject.Parse(cmdLine));
143 }
144
145 // exit
146 return;
147 }
148
149 // run in interactive mode, keep accepting commands until we get the shutdown command
150 bool quit = false;
151 while (!quit)
152 {
153 try
154 {
155 // read a line from the console
156 string line = Console.ReadLine();
157
158 // if stdin is closed (e.g., piped input finished), exit
159 if (line == null)
160 {
161 break;
162 }
163
164 // parse the line as a json object with one or more command keys (with values as parameters)
165 JObject root = JObject.Parse(line);
166
167 // execute the line
168 quit = execLine(root);
169 }
170 catch (Exception ex)
171 {
172 LogError(ex);
173 }
174 }
175 }
176
177 internal static void LogError(Exception ex)
178 {
179 Debug.WriteLine(ex);
180 ConsoleColor previousColor = Console.ForegroundColor;
181 Console.ForegroundColor = ConsoleColor.Red;
182 Console.WriteLine("Error: " + ex.Message);
183 Console.ForegroundColor = previousColor;
184 }
185
186 internal static void LogWarning(string message)
187 {
188 Debug.WriteLine(message);
189 ConsoleColor previousColor = Console.ForegroundColor;
190 Console.ForegroundColor = ConsoleColor.Yellow;
191 Console.WriteLine("Warning: " + message);
192 Console.ForegroundColor = previousColor;
193 }
194
195 static SortedList<string, string> GetAllInstalledAppsIds()
196 {
197 // GUID taken from https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid
198 var FOLDERID_AppsFolder = new Guid("{1e87508d-89c2-42f0-8a7e-645a0f50ca58}");
199 ShellObject appsFolder = (ShellObject)KnownFolderHelper.FromKnownFolderId(FOLDERID_AppsFolder);
200 var appIds = new SortedList<string, string>();
201
202 foreach (var app in (IKnownFolder)appsFolder)
203 {
204 string appName = app.Name.ToLowerInvariant();
205 if (appIds.ContainsKey(appName))
206 {
207 Debug.WriteLine("Key has multiple values: " + appName);
208 }
209 else
210 {
211 // The ParsingName property is the AppUserModelID
212 appIds.Add(appName, app.ParsingName);
213 }
214 }
215
216 return appIds;
217 }
218
219 static void SetMasterVolume(int pct)
220 {
221 // Using Windows Core Audio API via COM interop
222 try
223 {
224 var deviceEnumerator = (IMMDeviceEnumerator)new MMDeviceEnumerator();
225 deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out IMMDevice device);
226 var audioEndpointVolumeGuid = typeof(IAudioEndpointVolume).GUID;
227 device.Activate(ref audioEndpointVolumeGuid, 0, IntPtr.Zero, out object obj);
228 var audioEndpointVolume = (IAudioEndpointVolume)obj;
229 audioEndpointVolume.GetMasterVolumeLevelScalar(out float currentVolume);
230 s_savedVolumePct = currentVolume * 100.0;
231 audioEndpointVolume.SetMasterVolumeLevelScalar(pct / 100.0f, Guid.Empty);
232 }
233 catch (Exception ex)
234 {
235 Debug.WriteLine("Failed to set volume: " + ex.Message);
236 }
237 }
238
239 static void RestoreMasterVolume()
240 {
241 // Using Windows Core Audio API via COM interop
242 try
243 {
244 var deviceEnumerator = (IMMDeviceEnumerator)new MMDeviceEnumerator();
245 deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out IMMDevice device);
246 var audioEndpointVolumeGuid = typeof(IAudioEndpointVolume).GUID;
247 device.Activate(ref audioEndpointVolumeGuid, 0, IntPtr.Zero, out object obj);
248 var audioEndpointVolume = (IAudioEndpointVolume)obj;
249 audioEndpointVolume.SetMasterVolumeLevelScalar((float)(s_savedVolumePct / 100.0), Guid.Empty);
250 }
251 catch (Exception ex)
252 {
253 Debug.WriteLine("Failed to restore volume: " + ex.Message);
254 }
255 }
256
257 static void SetMasterMute(bool mute)
258 {
259 // Using Windows Core Audio API via COM interop
260 try
261 {
262 var deviceEnumerator = (IMMDeviceEnumerator)new MMDeviceEnumerator();
263 deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out IMMDevice device);
264 var audioEndpointVolumeGuid = typeof(IAudioEndpointVolume).GUID;
265 device.Activate(ref audioEndpointVolumeGuid, 0, IntPtr.Zero, out object obj);
266 var audioEndpointVolume = (IAudioEndpointVolume)obj;
267 audioEndpointVolume.GetMute(out bool currentMute);
268 Debug.WriteLine("Current Mute:" + currentMute);
269 audioEndpointVolume.SetMute(mute, Guid.Empty);
270 }
271 catch (Exception ex)
272 {
273 Debug.WriteLine("Failed to set mute: " + ex.Message);
274 }
275 }
276
277 static string ResolveProcessNameFromFriendlyName(string friendlyName)
278 {
279 string path = (string)s_friendlyNameToPath[friendlyName.ToLowerInvariant()];
280 if (path != null)
281 {
282 return Path.GetFileNameWithoutExtension(path);
283 }
284 else
285 {
286 return friendlyName;
287 }
288 }
289
290 static IntPtr FindProcessWindowHandle(string processName)
291 {
292 processName = ResolveProcessNameFromFriendlyName(processName);
293 Process[] processes = Process.GetProcessesByName(processName);
294 // loop through the processes that match the name; raise the first one that has a main window
295 foreach (Process p in processes)
296 {
297 if (p.MainWindowHandle != IntPtr.Zero)
298 {
299 return p.MainWindowHandle;
300 }
301 }
302
303 // Try to find by window title if we haven't found it and bring it forward
304 return FindWindowByTitle(processName).hWnd;
305 }
306
307 // given part of a process name, raise the window of that process to the top level
308 static void RaiseWindow(string processName)
309 {
310 processName = ResolveProcessNameFromFriendlyName(processName);
311 Process[] processes = Process.GetProcessesByName(processName);
312 // loop through the processes that match the name; raise the first one that has a main window
313 foreach (Process p in processes)
314 {
315 if (p.MainWindowHandle != IntPtr.Zero)
316 {
317 SetForegroundWindow(p.MainWindowHandle);
318 Interaction.AppActivate(p.Id);
319 return;
320 }
321 }
322
323 // this means all the applications processes are running in the background. This happens for edge and chrome browsers.
324 string path = (string)s_friendlyNameToPath[processName];
325 if (path != null)
326 {
327 Process.Start(path);
328 }
329 else
330 {
331 // Try to find by window title if we haven't found it and bring it forward
332 (nint hWnd1, int pid) = FindWindowByTitle(processName);
333
334 if (hWnd1 != nint.Zero)
335 {
336 SetForegroundWindow(hWnd1);
337 Interaction.AppActivate(pid);
338 }
339 }
340 }
341
342 static void MaximizeWindow(string processName)
343 {
344 processName = ResolveProcessNameFromFriendlyName(processName);
345 Process[] processes = Process.GetProcessesByName(processName);
346 // loop through the processes that match the name; raise the first one that has a main window
347 foreach (Process p in processes)
348 {
349 if (p.MainWindowHandle != IntPtr.Zero)
350 {
351 uint WM_SYSCOMMAND = 0x112;
352 uint SC_MAXIMIZE = 0xf030;
353 SendMessage(p.MainWindowHandle, WM_SYSCOMMAND, SC_MAXIMIZE, IntPtr.Zero);
354 SetForegroundWindow(p.MainWindowHandle);
355 Interaction.AppActivate(p.Id);
356 return;
357 }
358 }
359
360 // if we haven't found what we are looking for let's enumerate the top level windows and try that way
361 (nint hWnd, int pid) = FindWindowByTitle(processName);
362 if (hWnd != nint.Zero)
363 {
364 uint WM_SYSCOMMAND = 0x112;
365 uint SC_MAXIMIZE = 0xf030;
366 SendMessage(hWnd, WM_SYSCOMMAND, SC_MAXIMIZE, IntPtr.Zero);
367 SetForegroundWindow(hWnd);
368 Interaction.AppActivate(pid);
369 }
370 }
371
372 static void MinimizeWindow(string processName)
373 {
374 processName = ResolveProcessNameFromFriendlyName(processName);
375 Process[] processes = Process.GetProcessesByName(processName);
376 // loop through the processes that match the name; raise the first one that has a main window
377 foreach (Process p in processes)
378 {
379 if (p.MainWindowHandle != IntPtr.Zero)
380 {
381 uint WM_SYSCOMMAND = 0x112;
382 uint SC_MINIMIZE = 0xF020;
383 SendMessage(p.MainWindowHandle, WM_SYSCOMMAND, SC_MINIMIZE, IntPtr.Zero);
384 break;
385 }
386 }
387
388 // if we haven't found what we are looking for let's enumerate the top level windows and try that way
389 (nint hWnd, int pid) = FindWindowByTitle(processName);
390 if (hWnd != nint.Zero)
391 {
392 uint WM_SYSCOMMAND = 0x112;
393 uint SC_MINIMIZE = 0xF020;
394 SendMessage(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, IntPtr.Zero);
395 SetForegroundWindow(hWnd);
396 Interaction.AppActivate(pid);
397 }
398 }
399
400 static void TileWindowPair(string processName1, string processName2)
401 {
402 // find both processes
403 // TODO: Update this to account for UWP apps (e.g. calculator). UWPs are hosted by ApplicationFrameHost.exe
404 processName1 = ResolveProcessNameFromFriendlyName(processName1);
405 Process[] processes1 = Process.GetProcessesByName(processName1);
406 IntPtr hWnd1 = IntPtr.Zero;
407 IntPtr hWnd2 = IntPtr.Zero;
408 int pid1 = -1;
409 int pid2 = -1;
410
411 foreach (Process p in processes1)
412 {
413 if (p.MainWindowHandle != IntPtr.Zero)
414 {
415 hWnd1 = p.MainWindowHandle;
416 pid1 = p.Id;
417 break;
418 }
419 }
420
421 // If no process found by name, search by window title
422 if (hWnd1 == IntPtr.Zero)
423 {
424 (hWnd1, pid1) = FindWindowByTitle(processName1);
425 }
426
427 processName2 = ResolveProcessNameFromFriendlyName(processName2);
428 Process[] processes2 = Process.GetProcessesByName(processName2);
429 foreach (Process p in processes2)
430 {
431 if (p.MainWindowHandle != IntPtr.Zero)
432 {
433 hWnd2 = p.MainWindowHandle;
434 pid2 = p.Id;
435 break;
436 }
437 }
438
439 // If no process found by name, search by window title
440 if (hWnd2 == IntPtr.Zero)
441 {
442 (hWnd2, pid2) = FindWindowByTitle(processName2);
443 }
444
445 if (hWnd1 != IntPtr.Zero && hWnd2 != IntPtr.Zero)
446 {
447 // TODO: handle multiple monitors
448 // get the screen size
449 IntPtr desktopHandle = GetDesktopWindow();
450 RECT desktopRect = new RECT();
451 GetWindowRect(desktopHandle, ref desktopRect);
452 // get the dimensions of the taskbar
453 // find the taskbar window
454 IntPtr taskbarHandle = IntPtr.Zero;
455 IntPtr hWnd = IntPtr.Zero;
456 while ((hWnd = FindWindowEx(IntPtr.Zero, hWnd, "Shell_TrayWnd", null)) != IntPtr.Zero)
457 {
458 // find the taskbar window's child
459 taskbarHandle = FindWindowEx(hWnd, IntPtr.Zero, "ReBarWindow32", null);
460 if (taskbarHandle != IntPtr.Zero)
461 {
462 break;
463 }
464 }
465 if (hWnd == IntPtr.Zero)
466 {
467 Debug.WriteLine("Taskbar not found");
468 return;
469 }
470 else
471 {
472 RECT taskbarRect = new RECT();
473 GetWindowRect(hWnd, ref taskbarRect);
474 Debug.WriteLine("Taskbar Rect: " + taskbarRect.Left + ", " + taskbarRect.Top + ", " + taskbarRect.Right + ", " + taskbarRect.Bottom);
475 // TODO: handle left, top, right and nonexistant taskbars
476 // subtract the taskbar height from the screen height
477 desktopRect.Bottom -= (int)((taskbarRect.Bottom - taskbarRect.Top) / 2);
478 }
479 // set the window positions using the shellRect and making sure the windows are visible
480 int halfwidth = (desktopRect.Right - desktopRect.Left) / 2;
481 IntPtr HWND_TOP = IntPtr.Zero;
482 uint showWindow = 0x40;
483 SetWindowPos(hWnd1, HWND_TOP, desktopRect.Left, desktopRect.Top, halfwidth, desktopRect.Bottom, showWindow);
484 SetForegroundWindow(hWnd1);
485 Interaction.AppActivate(pid1);
486 SetWindowPos(hWnd2, HWND_TOP, desktopRect.Left + halfwidth, desktopRect.Top, halfwidth, desktopRect.Bottom, showWindow);
487 SetForegroundWindow(hWnd2);
488 Interaction.AppActivate(pid2);
489 }
490 }
491
492 /// <summary>
493 /// Finds a top-level window by searching for a partial match in the window title.
494 /// </summary>
495 /// <param name="titleSearch">The text to search for in window titles (case-insensitive).</param>
496 /// <returns>A tuple containing the window handle and process ID, or (IntPtr.Zero, -1) if not found.</returns>
497 static (IntPtr hWnd, int pid) FindWindowByTitle(string titleSearch)
498 {
499 IntPtr foundHandle = IntPtr.Zero;
500 int foundPid = -1;
501 StringBuilder windowTitle = new StringBuilder(256);
502
503 EnumWindows((hWnd, lParam) =>
504 {
505 // Only consider visible windows
506 if (!IsWindowVisible(hWnd))
507 {
508 return true; // Continue enumeration
509 }
510
511 // Get window title
512 int length = GetWindowText(hWnd, windowTitle, windowTitle.Capacity);
513 if (length > 0)
514 {
515 string title = windowTitle.ToString();
516 // Case-insensitive partial match
517 if (title.Contains(titleSearch, StringComparison.OrdinalIgnoreCase))
518 {
519 foundHandle = hWnd;
520 GetWindowThreadProcessId(hWnd, out uint pid);
521 foundPid = (int)pid;
522 return false; // Stop enumeration
523 }
524 }
525 return true; // Continue enumeration
526 }, IntPtr.Zero);
527
528 return (foundHandle, foundPid);
529 }
530
531 // given a friendly name, check if it's running and if not, start it; if it's running raise it to the top level
532 static void OpenApplication(string friendlyName)
533 {
534 // check to see if the application is running
535 Process[] processes = Process.GetProcessesByName(friendlyName);
536 if (processes.Length == 0)
537 {
538 // if not, start it
539 Debug.WriteLine("Starting " + friendlyName);
540 string path = (string)s_friendlyNameToPath[friendlyName.ToLowerInvariant()];
541 if (path != null)
542 {
543 ProcessStartInfo psi = new ProcessStartInfo()
544 {
545 FileName = path,
546 UseShellExecute = true
547 };
548
549 // do we have a specific startup directory for this application?
550 if (s_sortedList.TryGetValue(friendlyName.ToLowerInvariant(), out string[] value) && value.Length > 1)
551 {
552 psi.WorkingDirectory = Environment.ExpandEnvironmentVariables("%" + value[1] + "%") ?? string.Empty;
553 }
554
555 // do we have any specific command line arguments for this application?
556 if (s_sortedList.TryGetValue(friendlyName.ToLowerInvariant(), out string[] args) && value.Length > 2)
557 {
558 psi.Arguments = string.Join(" ", args.Skip(2));
559 }
560
561 try
562 {
563 Process.Start(psi);
564 }
565 catch (System.ComponentModel.Win32Exception)
566 {
567 psi.FileName = friendlyName;
568
569 // alternate start method
570 Process.Start(psi);
571 }
572 }
573 else
574 {
575 string appModelUserID = (string)s_friendlyNameToId[friendlyName.ToLowerInvariant()];
576 if (appModelUserID != null)
577 {
578 try
579 {
580 Process.Start("explorer.exe", @" shell:appsFolder\" + appModelUserID);
581 }
582 catch { }
583 }
584 }
585 }
586 else
587 {
588 // if so, raise it to the top level
589 Debug.WriteLine("Raising " + friendlyName);
590 RaiseWindow(friendlyName);
591 }
592 }
593
594 // close application
595 static void CloseApplication(string friendlyName)
596 {
597 // check to see if the application is running
598 string processName = ResolveProcessNameFromFriendlyName(friendlyName);
599 Process[] processes = Process.GetProcessesByName(processName);
600 if (processes.Length != 0)
601 {
602 // if so, close it
603 Debug.WriteLine("Closing " + friendlyName);
604 foreach (Process p in processes)
605 {
606 if (p.MainWindowHandle != IntPtr.Zero)
607 {
608 p.CloseMainWindow();
609 }
610 }
611 }
612 }
613
614 private static void SetDesktopWallpaper(string imagePath)
615 {
616 SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, imagePath, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
617 }
618
619 /// <summary>
620 /// Creates virtual desktops from a JSON array of desktop names.
621 /// </summary>
622 /// <param name="jsonValue">JSON array containing desktop names, e.g., ["Work", "Personal", "Gaming"]</param>
623 static void CreateDesktop(string jsonValue)
624 {
625 try
626 {
627 // Parse the JSON array of desktop names
628 JArray desktopNames = JArray.Parse(jsonValue);
629
630 if (desktopNames == null || desktopNames.Count == 0)
631 {
632 desktopNames = ["desktop X"];
633 }
634
635 if (s_virtualDesktopManagerInternal == null)
636 {
637 Debug.WriteLine($"Failed to get Virtual Desktop Manager Internal");
638 return;
639 }
640
641 foreach (JToken desktopNameToken in desktopNames)
642 {
643 string desktopName = desktopNameToken.ToString();
644
645
646 try
647 {
648 // Create a new virtual desktop
649 IVirtualDesktop newDesktop = s_virtualDesktopManagerInternal.CreateDesktop();
650
651 if (newDesktop != null)
652 {
653 // Set the desktop name (Windows 10 build 20231+ / Windows 11)
654 try
655 {
656 // TODO: debug & get working
657 // Works in .NET framework but not .NET
658 //s_virtualDesktopManagerInternal_BUGBUG.SetDesktopName(newDesktop, desktopName);
659 //Debug.WriteLine($"Created virtual desktop: {desktopName}");
660 }
661 catch (Exception ex2)
662 {
663 // Older Windows version - name setting not supported
664 Debug.WriteLine($"Created virtual desktop (naming not supported on this Windows version): {ex2.Message}");
665 }
666 }
667 }
668 catch (Exception ex)
669 {
670 Debug.WriteLine($"Failed to create desktop '{desktopName}': {ex.Message}");
671 }
672 }
673 }
674 catch (JsonException ex)
675 {
676 Debug.WriteLine($"Failed to parse desktop names JSON: {ex.Message}");
677 }
678 catch (Exception ex)
679 {
680 Debug.WriteLine($"Error creating desktops: {ex.Message}");
681 }
682 }
683
684 static void SwitchDesktop(string desktopIdentifier)
685 {
686 if (!int.TryParse(desktopIdentifier, out int index))
687 {
688 // Try to find the desktop by name
689 s_virtualDesktopManagerInternal.SwitchDesktop(FindDesktopByName(desktopIdentifier));
690 }
691 else
692 {
693 SwitchDesktop(index);
694 }
695 }
696
697 static void SwitchDesktop(int index)
698 {
699 s_virtualDesktopManagerInternal.GetDesktops(out IObjectArray desktops);
700 desktops.GetAt(index, typeof(IVirtualDesktop).GUID, out object od);
701
702 // BUGBUG: different windows versions use different COM interfaces
703 // Different Windows versions use different COM interfaces for desktop switching
704 // Windows 11 22H2 (build 22621) and later use the updated interface
705 if (OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22621))
706 {
707 // Use the BUGBUG interface for Windows 11 22H2+
708 s_virtualDesktopManagerInternal_BUGBUG.SwitchDesktopWithAnimation((IVirtualDesktop)od);
709 }
710 else if (OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22000))
711 {
712 // Windows 11 21H2 (build 22000)
713 s_virtualDesktopManagerInternal.SwitchDesktopWithAnimation((IVirtualDesktop)od);
714 }
715 else
716 {
717 // Windows 10 - use the original interface
718 s_virtualDesktopManagerInternal.SwitchDesktopAndMoveForegroundView((IVirtualDesktop)od);
719 }
720
721 Marshal.ReleaseComObject(desktops);
722 }
723
724 static void BumpDesktopIndex(int bump)
725 {
726 IVirtualDesktop desktop = s_virtualDesktopManagerInternal.GetCurrentDesktop();
727 int index = GetDesktopIndex(desktop);
728 int count = s_virtualDesktopManagerInternal.GetCount();
729
730 if (index == -1)
731 {
732 Debug.WriteLine("Undable to get the index of the current desktop");
733 return;
734 }
735
736 index += bump;
737
738 if (index > count)
739 {
740 index = 0;
741 }
742 else if (index < 0)
743 {
744 index = count - 1;
745 }
746
747 SwitchDesktop(index);
748 }
749
750 static IVirtualDesktop FindDesktopByName(string name)
751 {
752 int count = s_virtualDesktopManagerInternal.GetCount();
753
754 s_virtualDesktopManagerInternal.GetDesktops(out IObjectArray desktops);
755 for (int i = 0; i < count; i++)
756 {
757 desktops.GetAt(i, typeof(IVirtualDesktop).GUID, out object od);
758
759 if (string.Equals(((IVirtualDesktop)od).GetName(), name, StringComparison.OrdinalIgnoreCase))
760 {
761 Marshal.ReleaseComObject(desktops);
762 return (IVirtualDesktop)od;
763 }
764 }
765
766 Marshal.ReleaseComObject(desktops);
767
768 return null;
769 }
770
771 static int GetDesktopIndex(IVirtualDesktop desktop)
772 {
773 int index = -1;
774 int count = s_virtualDesktopManagerInternal.GetCount();
775
776 s_virtualDesktopManagerInternal.GetDesktops(out IObjectArray desktops);
777 for (int i = 0; i < count; i++)
778 {
779 desktops.GetAt(i, typeof(IVirtualDesktop).GUID, out object od);
780
781 if (desktop.GetId() == ((IVirtualDesktop)od).GetId())
782 {
783 Marshal.ReleaseComObject(desktops);
784 return i;
785 }
786 }
787
788 Marshal.ReleaseComObject(desktops);
789
790 return -1;
791 }
792
793 /// <summary>
794 ///
795 /// </summary>
796 /// <param name="value"></param>
797 /// <remarks>Currently not working correction, returns ACCESS_DENIED // TODO: investigate</remarks>
798 static void MoveWindowToDesktop(JToken value)
799 {
800 string process = value.SelectToken("process").ToString();
801 string desktop = value.SelectToken("desktop").ToString();
802 if (string.IsNullOrEmpty(process))
803 {
804 Debug.WriteLine("No process name supplied");
805 return;
806 }
807
808 if (string.IsNullOrEmpty(desktop))
809 {
810 Debug.WriteLine("No desktop id supplied");
811 return;
812 }
813
814 IntPtr hWnd = FindProcessWindowHandle(process);
815
816 if (int.TryParse(desktop, out int desktopIndex))
817 {
818 s_virtualDesktopManagerInternal.GetDesktops(out IObjectArray desktops);
819 if (desktopIndex < 1 || desktopIndex > s_virtualDesktopManagerInternal.GetCount())
820 {
821 Debug.WriteLine("Desktop index out of range");
822 Marshal.ReleaseComObject(desktops);
823 return;
824 }
825 desktops.GetAt(desktopIndex - 1, typeof(IVirtualDesktop).GUID, out object od);
826 Guid g = ((IVirtualDesktop)od).GetId();
827 s_virtualDesktopManager.MoveWindowToDesktop(hWnd, ref g);
828 Marshal.ReleaseComObject(desktops);
829 return;
830 }
831
832 IVirtualDesktop ivd = FindDesktopByName(desktop);
833 if (ivd is not null)
834 {
835 Guid desktopGuid = ivd.GetId();
836 s_virtualDesktopManager.MoveWindowToDesktop(hWnd, ref desktopGuid);
837 }
838 }
839
840 static void PinWindow(string processName)
841 {
842 IntPtr hWnd = FindProcessWindowHandle(processName);
843
844 if (hWnd != IntPtr.Zero)
845 {
846 s_applicationViewCollection.GetViewForHwnd(hWnd, out IApplicationView view);
847
848 if (view is not null)
849 {
850 s_virtualDesktopPinnedApps.PinView((IApplicationView)view);
851 }
852 }
853 else
854 {
855 Console.WriteLine($"The window handle for '{processName}' could not be found");
856 }
857 }
858
859 static IVirtualDesktopManagerInternal GetVirtualDesktopManagerInternal()
860 {
861 try
862 {
863 IServiceProvider shellServiceProvider = (IServiceProvider)Activator.CreateInstance(
864 Type.GetTypeFromCLSID(CLSID_ImmersiveShell));
865
866 shellServiceProvider.QueryService(
867 CLSID_VirtualDesktopManagerInternal,
868 typeof(IVirtualDesktopManagerInternal).GUID,
869 out object objVirtualDesktopManagerInternal);
870
871 return (IVirtualDesktopManagerInternal)objVirtualDesktopManagerInternal;
872 }
873 catch
874 {
875 return null;
876 }
877 }
878
879 static bool execLine(JObject root)
880 {
881 var quit = false;
882 foreach (var kvp in root)
883 {
884 string key = kvp.Key;
885 string value = kvp.Value.ToString();
886 switch (key)
887 {
888 case "launchProgram":
889 OpenApplication(value);
890 break;
891 case "closeProgram":
892 CloseApplication(value);
893 break;
894 case "maximize":
895 MaximizeWindow(value);
896 break;
897 case "minimize":
898 MinimizeWindow(value);
899 break;
900 case "switchTo":
901 RaiseWindow(value);
902 break;
903 case "quit":
904 quit = true;
905 break;
906 case "tile":
907 string[] apps = value.Split(',');
908 if (apps.Length == 2)
909 {
910 TileWindowPair(apps[0], apps[1]);
911 }
912 break;
913 case "volume":
914 int pct = 0;
915 if (int.TryParse(value, out pct))
916 {
917 SetMasterVolume(pct);
918 }
919 break;
920 case "restoreVolume":
921 RestoreMasterVolume();
922 break;
923 case "mute":
924 bool mute = false;
925 if (bool.TryParse(value, out mute))
926 {
927 SetMasterMute(mute);
928 }
929 break;
930 case "listAppNames":
931 var installedApps = GetAllInstalledAppsIds();
932 Console.WriteLine(JsonConvert.SerializeObject(installedApps.Keys));
933 break;
934 case "setWallpaper":
935 SetDesktopWallpaper(value);
936 break;
937 case "applyTheme":
938 bool result = ApplyTheme(value);
939 break;
940 case "listThemes":
941 var themes = GetInstalledThemes();
942 Console.WriteLine(JsonConvert.SerializeObject(themes));
943 break;
944 case "setThemeMode":
945 // value can be "light", "dark", "toggle", or boolean
946 if (value.Equals("toggle", StringComparison.OrdinalIgnoreCase))
947 {
948 ToggleLightDarkMode();
949 }
950 else
951 {
952 bool useLightMode;
953 if (bool.TryParse(value, out useLightMode))
954 {
955 SetLightDarkMode(useLightMode);
956 }
957 else if (value.Equals("light", StringComparison.OrdinalIgnoreCase))
958 {
959 SetLightDarkMode(true);
960 }
961 else if (value.Equals("dark", StringComparison.OrdinalIgnoreCase))
962 {
963 SetLightDarkMode(false);
964 }
965 }
966 break;
967 case "createDesktop":
968 CreateDesktop(value);
969 break;
970 case "switchDesktop":
971 SwitchDesktop(value);
972 break;
973 case "nextDesktop":
974 BumpDesktopIndex(1);
975 break;
976 case "previousDesktop":
977 BumpDesktopIndex(-1);
978 break;
979 case "moveWindowToDesktop":
980 MoveWindowToDesktop(kvp.Value);
981 break;
982 case "pinWindow":
983 PinWindow(value);
984 break;
985 case "toggleNotifications":
986 ShellExecute(IntPtr.Zero, "open", "ms-actioncenter:", null, null, 1);
987 break;
988 case "debug":
989 Debugger.Launch();
990 break;
991 case "toggleAirplaneMode":
992 SetAirplaneMode(bool.Parse(value));
993 break;
994 case "listWifiNetworks":
995 ListWifiNetworks();
996 break;
997 case "connectWifi":
998 JObject netInfo = JObject.Parse(value);
999 string ssid = netInfo.Value<string>("ssid");
1000 string password = netInfo["password"] is not null ? netInfo.Value<string>("password") : "";
1001 ConnectToWifi(ssid, password);
1002 break;
1003 case "disconnectWifi":
1004 DisconnectFromWifi();
1005 break;
1006 case "setTextSize":
1007 if (int.TryParse(value, out int textSizePct))
1008 {
1009 SetTextSize(textSizePct);
1010 }
1011 break;
1012 case "setScreenResolution":
1013 SetDisplayResolution(kvp.Value);
1014 break;
1015 case "listResolutions":
1016 ListDisplayResolutions();
1017 break;
1018
1019 // ===== Settings Actions (50 new handlers) =====
1020
1021 // Network Settings
1022 case "BluetoothToggle":
1023 HandleBluetoothToggle(value);
1024 break;
1025 case "enableWifi":
1026 HandleEnableWifi(value);
1027 break;
1028 case "enableMeteredConnections":
1029 HandleEnableMeteredConnections(value);
1030 break;
1031
1032 // Display Settings
1033 case "AdjustScreenBrightness":
1034 HandleAdjustScreenBrightness(value);
1035 break;
1036 case "EnableBlueLightFilterSchedule":
1037 HandleEnableBlueLightFilterSchedule(value);
1038 break;
1039 case "adjustColorTemperature":
1040 HandleAdjustColorTemperature(value);
1041 break;
1042 case "DisplayScaling":
1043 HandleDisplayScaling(value);
1044 break;
1045 case "AdjustScreenOrientation":
1046 HandleAdjustScreenOrientation(value);
1047 break;
1048 case "DisplayResolutionAndAspectRatio":
1049 HandleDisplayResolutionAndAspectRatio(value);
1050 break;
1051 case "RotationLock":
1052 HandleRotationLock(value);
1053 break;
1054
1055 // Personalization Settings
1056 case "SystemThemeMode":
1057 HandleSystemThemeMode(value);
1058 break;
1059 case "EnableTransparency":
1060 HandleEnableTransparency(value);
1061 break;
1062 case "ApplyColorToTitleBar":
1063 HandleApplyColorToTitleBar(value);
1064 break;
1065 case "HighContrastTheme":
1066 HandleHighContrastTheme(value);
1067 break;
1068
1069 // Taskbar Settings
1070 case "AutoHideTaskbar":
1071 HandleAutoHideTaskbar(value);
1072 break;
1073 case "TaskbarAlignment":
1074 HandleTaskbarAlignment(value);
1075 break;
1076 case "TaskViewVisibility":
1077 HandleTaskViewVisibility(value);
1078 break;
1079 case "ToggleWidgetsButtonVisibility":
1080 HandleToggleWidgetsButtonVisibility(value);
1081 break;
1082 case "ShowBadgesOnTaskbar":
1083 HandleShowBadgesOnTaskbar(value);
1084 break;
1085 case "DisplayTaskbarOnAllMonitors":
1086 HandleDisplayTaskbarOnAllMonitors(value);
1087 break;
1088 case "DisplaySecondsInSystrayClock":
1089 HandleDisplaySecondsInSystrayClock(value);
1090 break;
1091
1092 // Mouse Settings
1093 case "MouseCursorSpeed":
1094 HandleMouseCursorSpeed(value);
1095 break;
1096 case "MouseWheelScrollLines":
1097 HandleMouseWheelScrollLines(value);
1098 break;
1099 case "setPrimaryMouseButton":
1100 HandleSetPrimaryMouseButton(value);
1101 break;
1102 case "EnhancePointerPrecision":
1103 HandleEnhancePointerPrecision(value);
1104 break;
1105 case "AdjustMousePointerSize":
1106 HandleAdjustMousePointerSize(value);
1107 break;
1108 case "mousePointerCustomization":
1109 HandleMousePointerCustomization(value);
1110 break;
1111
1112 // Touchpad Settings
1113 case "EnableTouchPad":
1114 HandleEnableTouchPad(value);
1115 break;
1116 case "TouchpadCursorSpeed":
1117 HandleTouchpadCursorSpeed(value);
1118 break;
1119
1120 // Privacy Settings
1121 case "ManageMicrophoneAccess":
1122 HandleManageMicrophoneAccess(value);
1123 break;
1124 case "ManageCameraAccess":
1125 HandleManageCameraAccess(value);
1126 break;
1127 case "ManageLocationAccess":
1128 HandleManageLocationAccess(value);
1129 break;
1130
1131 // Power Settings
1132 case "BatterySaverActivationLevel":
1133 HandleBatterySaverActivationLevel(value);
1134 break;
1135 case "setPowerModePluggedIn":
1136 HandleSetPowerModePluggedIn(value);
1137 break;
1138 case "SetPowerModeOnBattery":
1139 HandleSetPowerModeOnBattery(value);
1140 break;
1141
1142 // Gaming Settings
1143 case "enableGameMode":
1144 HandleEnableGameMode(value);
1145 break;
1146
1147 // Accessibility Settings
1148 case "EnableNarratorAction":
1149 HandleEnableNarratorAction(value);
1150 break;
1151 case "EnableMagnifier":
1152 HandleEnableMagnifier(value);
1153 break;
1154 case "enableStickyKeys":
1155 HandleEnableStickyKeysAction(value);
1156 break;
1157 case "EnableFilterKeysAction":
1158 HandleEnableFilterKeysAction(value);
1159 break;
1160 case "MonoAudioToggle":
1161 HandleMonoAudioToggle(value);
1162 break;
1163
1164 // File Explorer Settings
1165 case "ShowFileExtensions":
1166 HandleShowFileExtensions(value);
1167 break;
1168 case "ShowHiddenAndSystemFiles":
1169 HandleShowHiddenAndSystemFiles(value);
1170 break;
1171
1172 // Time & Region Settings
1173 case "AutomaticTimeSettingAction":
1174 HandleAutomaticTimeSettingAction(value);
1175 break;
1176 case "AutomaticDSTAdjustment":
1177 HandleAutomaticDSTAdjustment(value);
1178 break;
1179
1180 // Focus Assist Settings
1181 case "EnableQuietHours":
1182 HandleEnableQuietHours(value);
1183 break;
1184
1185 // Multi-Monitor Settings
1186 case "RememberWindowLocations":
1187 HandleRememberWindowLocationsAction(value);
1188 break;
1189 case "MinimizeWindowsOnMonitorDisconnectAction":
1190 HandleMinimizeWindowsOnMonitorDisconnectAction(value);
1191 break;
1192
1193 default:
1194 Debug.WriteLine("Unknown command: " + key);
1195 break;
1196 }
1197 }
1198 return quit;
1199 }
1200
1201 /// <summary>
1202 /// Sets the airplane mode state using the Radio Management API.
1203 /// </summary>
1204 /// <param name="enable">True to enable airplane mode, false to disable.</param>
1205 static void SetAirplaneMode(bool enable)
1206 {
1207 IRadioManager radioManager = null;
1208 try
1209 {
1210 // Create the Radio Management API COM object
1211 Type radioManagerType = Type.GetTypeFromCLSID(CLSID_RadioManagementAPI);
1212 if (radioManagerType == null)
1213 {
1214 Debug.WriteLine("Failed to get Radio Management API type");
1215 return;
1216 }
1217
1218 object obj = Activator.CreateInstance(radioManagerType);
1219 radioManager = (IRadioManager)obj;
1220
1221 if (radioManager == null)
1222 {
1223 Debug.WriteLine("Failed to create Radio Manager instance");
1224 return;
1225 }
1226
1227 // Get current state (for logging)
1228 int hr = radioManager.GetSystemRadioState(out int currentState, out int _, out int _);
1229 if (hr < 0)
1230 {
1231 Debug.WriteLine($"Failed to get system radio state: HRESULT 0x{hr:X8}");
1232 return;
1233 }
1234
1235 // currentState: 0 = airplane mode ON (radios off), 1 = airplane mode OFF (radios on)
1236 bool airplaneModeCurrentlyOn = currentState == 0;
1237 Debug.WriteLine($"Current airplane mode state: {(airplaneModeCurrentlyOn ? "on" : "off")}");
1238
1239 // Set the new state
1240 // bEnabled: 0 = turn airplane mode ON (disable radios), 1 = turn airplane mode OFF (enable radios)
1241 int newState = enable ? 0 : 1;
1242 hr = radioManager.SetSystemRadioState(newState);
1243 if (hr < 0)
1244 {
1245 Debug.WriteLine($"Failed to set system radio state: HRESULT 0x{hr:X8}");
1246 return;
1247 }
1248
1249 Debug.WriteLine($"Airplane mode set to: {(enable ? "on" : "off")}");
1250 }
1251 catch (COMException ex)
1252 {
1253 Debug.WriteLine($"COM Exception setting airplane mode: {ex.Message} (HRESULT: 0x{ex.HResult:X8})");
1254 }
1255 catch (Exception ex)
1256 {
1257 Debug.WriteLine($"Failed to set airplane mode: {ex.Message}");
1258 }
1259 finally
1260 {
1261 if (radioManager != null)
1262 {
1263 Marshal.ReleaseComObject(radioManager);
1264 }
1265 }
1266 }
1267
1268 /// <summary>
1269 /// Lists all WiFi networks currently in range.
1270 /// </summary>
1271 static void ListWifiNetworks()
1272 {
1273 IntPtr clientHandle = IntPtr.Zero;
1274 IntPtr wlanInterfaceList = IntPtr.Zero;
1275 IntPtr networkList = IntPtr.Zero;
1276
1277 try
1278 {
1279 // Open WLAN handle
1280 int result = WlanOpenHandle(2, IntPtr.Zero, out uint negotiatedVersion, out clientHandle);
1281 if (result != 0)
1282 {
1283 Debug.WriteLine($"Failed to open WLAN handle: {result}");
1284 return;
1285 }
1286
1287 // Enumerate wireless interfaces
1288 result = WlanEnumInterfaces(clientHandle, IntPtr.Zero, out wlanInterfaceList);
1289 if (result != 0)
1290 {
1291 Debug.WriteLine($"Failed to enumerate WLAN interfaces: {result}");
1292 return;
1293 }
1294
1295 WLAN_INTERFACE_INFO_LIST interfaceList = Marshal.PtrToStructure<WLAN_INTERFACE_INFO_LIST>(wlanInterfaceList);
1296
1297 if (interfaceList.dwNumberOfItems == 0)
1298 {
1299 Console.WriteLine("[]");
1300 return;
1301 }
1302
1303 var allNetworks = new List<object>();
1304
1305 for (int i = 0; i < interfaceList.dwNumberOfItems; i++)
1306 {
1307 WLAN_INTERFACE_INFO interfaceInfo = interfaceList.InterfaceInfo[i];
1308
1309 // Scan for networks (trigger a refresh)
1310 WlanScan(clientHandle, ref interfaceInfo.InterfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
1311
1312 // Small delay to allow scan to complete
1313 System.Threading.Thread.Sleep(100);
1314
1315 // Get available networks
1316 result = WlanGetAvailableNetworkList(clientHandle, ref interfaceInfo.InterfaceGuid, 0, IntPtr.Zero, out networkList);
1317 if (result != 0)
1318 {
1319 Debug.WriteLine($"Failed to get network list: {result}");
1320 continue;
1321 }
1322
1323 WLAN_AVAILABLE_NETWORK_LIST availableNetworkList = Marshal.PtrToStructure<WLAN_AVAILABLE_NETWORK_LIST>(networkList);
1324
1325 IntPtr networkPtr = networkList + 8; // Skip dwNumberOfItems and dwIndex
1326
1327 for (int j = 0; j < availableNetworkList.dwNumberOfItems; j++)
1328 {
1329 WLAN_AVAILABLE_NETWORK network = Marshal.PtrToStructure<WLAN_AVAILABLE_NETWORK>(networkPtr);
1330
1331 string ssid = Encoding.ASCII.GetString(network.dot11Ssid.SSID, 0, (int)network.dot11Ssid.SSIDLength);
1332
1333 if (!string.IsNullOrEmpty(ssid))
1334 {
1335 allNetworks.Add(new
1336 {
1337 SSID = ssid,
1338 SignalQuality = network.wlanSignalQuality,
1339 Secured = network.bSecurityEnabled,
1340 Connected = (network.dwFlags & 1) != 0 // WLAN_AVAILABLE_NETWORK_CONNECTED
1341 });
1342 }
1343
1344 networkPtr += Marshal.SizeOf<WLAN_AVAILABLE_NETWORK>();
1345 }
1346
1347 if (networkList != IntPtr.Zero)
1348 {
1349 WlanFreeMemory(networkList);
1350 networkList = IntPtr.Zero;
1351 }
1352 }
1353
1354 // Remove duplicates and sort by signal strength
1355 var uniqueNetworks = allNetworks
1356 .GroupBy(n => ((dynamic)n).SSID)
1357 .Select(g => g.OrderByDescending(n => ((dynamic)n).SignalQuality).First())
1358 .OrderByDescending(n => ((dynamic)n).SignalQuality)
1359 .ToList();
1360
1361 Console.WriteLine(JsonConvert.SerializeObject(uniqueNetworks));
1362 }
1363 catch (Exception ex)
1364 {
1365 Debug.WriteLine($"Error listing WiFi networks: {ex.Message}");
1366 Console.WriteLine("[]");
1367 }
1368 finally
1369 {
1370 if (networkList != IntPtr.Zero)
1371 WlanFreeMemory(networkList);
1372 if (wlanInterfaceList != IntPtr.Zero)
1373 WlanFreeMemory(wlanInterfaceList);
1374 if (clientHandle != IntPtr.Zero)
1375 WlanCloseHandle(clientHandle, IntPtr.Zero);
1376 }
1377 }
1378
1379 /// <summary>
1380 /// Connects to a WiFi network by name (SSID). If the network requires a password and one is provided,
1381 /// it will create a temporary profile. For networks with existing profiles, it connects using the profile.
1382 /// </summary>
1383 /// <param name="ssid">The SSID of the network to connect to.</param>
1384 /// <param name="password">Optional password for secured networks.</param>
1385 static void ConnectToWifi(string ssid, string password = null)
1386 {
1387 IntPtr clientHandle = IntPtr.Zero;
1388 IntPtr wlanInterfaceList = IntPtr.Zero;
1389
1390 try
1391 {
1392 // Open WLAN handle
1393 int result = WlanOpenHandle(2, IntPtr.Zero, out uint negotiatedVersion, out clientHandle);
1394 if (result != 0)
1395 {
1396 LogWarning($"Failed to open WLAN handle: {result}");
1397 return;
1398 }
1399
1400 // Enumerate wireless interfaces
1401 result = WlanEnumInterfaces(clientHandle, IntPtr.Zero, out wlanInterfaceList);
1402 if (result != 0)
1403 {
1404 LogWarning($"Failed to enumerate WLAN interfaces: {result}");
1405 return;
1406 }
1407
1408 WLAN_INTERFACE_INFO_LIST interfaceList = Marshal.PtrToStructure<WLAN_INTERFACE_INFO_LIST>(wlanInterfaceList);
1409
1410 if (interfaceList.dwNumberOfItems == 0)
1411 {
1412 LogWarning("No wireless interfaces found.");
1413 return;
1414 }
1415
1416 // Use the first available wireless interface
1417 WLAN_INTERFACE_INFO interfaceInfo = interfaceList.InterfaceInfo[0];
1418
1419 // If password is provided, create a profile and connect
1420 if (!string.IsNullOrEmpty(password))
1421 {
1422 string profileXml = GenerateWifiProfileXml(ssid, password);
1423
1424 result = WlanSetProfile(clientHandle, ref interfaceInfo.InterfaceGuid, 0, profileXml, null, true, IntPtr.Zero, out uint reasonCode);
1425 if (result != 0)
1426 {
1427 LogWarning($"Failed to set WiFi profile: {result}, reason: {reasonCode}");
1428 return;
1429 }
1430 }
1431
1432 // Set up connection parameters
1433 WLAN_CONNECTION_PARAMETERS connectionParams = new WLAN_CONNECTION_PARAMETERS
1434 {
1435 wlanConnectionMode = WLAN_CONNECTION_MODE.wlan_connection_mode_profile,
1436 strProfile = ssid,
1437 pDot11Ssid = IntPtr.Zero,
1438 pDesiredBssidList = IntPtr.Zero,
1439 dot11BssType = DOT11_BSS_TYPE.dot11_BSS_type_any,
1440 dwFlags = 0
1441 };
1442
1443 result = WlanConnect(clientHandle, ref interfaceInfo.InterfaceGuid, ref connectionParams, IntPtr.Zero);
1444 if (result != 0)
1445 {
1446 LogWarning($"Failed to connect to WiFi network '{ssid}': {result}");
1447 return;
1448 }
1449
1450 Debug.WriteLine($"Successfully initiated connection to WiFi network: {ssid}");
1451 Console.WriteLine($"Connecting to WiFi network: {ssid}");
1452 }
1453 catch (Exception ex)
1454 {
1455 LogError(ex);
1456 }
1457 finally
1458 {
1459 if (wlanInterfaceList != IntPtr.Zero)
1460 WlanFreeMemory(wlanInterfaceList);
1461 if (clientHandle != IntPtr.Zero)
1462 WlanCloseHandle(clientHandle, IntPtr.Zero);
1463 }
1464 }
1465
1466 /// <summary>
1467 /// Generates a WiFi profile XML for WPA2-Personal (PSK) networks.
1468 /// </summary>
1469 static string GenerateWifiProfileXml(string ssid, string password)
1470 {
1471 // Convert SSID to hex
1472 string ssidHex = BitConverter.ToString(Encoding.UTF8.GetBytes(ssid)).Replace("-", "");
1473
1474 return $@"<?xml version=""1.0""?>
1475<WLANProfile xmlns=""http://www.microsoft.com/networking/WLAN/profile/v1"">
1476 <name>{ssid}</name>
1477 <SSIDConfig>
1478 <SSID>
1479 <hex>{ssidHex}</hex>
1480 <name>{ssid}</name>
1481 </SSID>
1482 </SSIDConfig>
1483 <connectionType>ESS</connectionType>
1484 <connectionMode>auto</connectionMode>
1485 <MSM>
1486 <security>
1487 <authEncryption>
1488 <authentication>WPA2PSK</authentication>
1489 <encryption>AES</encryption>
1490 <useOneX>false</useOneX>
1491 </authEncryption>
1492 <sharedKey>
1493 <keyType>passPhrase</keyType>
1494 <protected>false</protected>
1495 <keyMaterial>{password}</keyMaterial>
1496 </sharedKey>
1497 </security>
1498 </MSM>
1499</WLANProfile>";
1500 }
1501
1502 /// <summary>
1503 /// Disconnects from the currently connected WiFi network.
1504 /// </summary>
1505 /// <summary>
1506 /// Sets the system text scaling factor (percentage).
1507 /// </summary>
1508 /// <param name="percentage">The text scaling percentage (100-225).</param>
1509 static void SetTextSize(int percentage)
1510 {
1511 try
1512 {
1513 if (percentage == -1)
1514 {
1515 percentage = new Random().Next(100, 225 + 1);
1516 }
1517
1518 // Clamp the percentage to valid range
1519 if (percentage < 100)
1520 {
1521 percentage = 100;
1522 }
1523 else if (percentage > 225)
1524 {
1525 percentage = 225;
1526 }
1527
1528 // Open the Settings app to the ease of access page
1529 Process.Start(new ProcessStartInfo
1530 {
1531 FileName = "ms-settings:easeofaccess",
1532 UseShellExecute = true
1533 });
1534
1535 // Use UI Automation to navigate and set the text size
1536 UIAutomation.SetTextSizeViaUIAutomation(percentage);
1537 }
1538 catch (Exception ex)
1539 {
1540 LogError(ex);
1541 }
1542 }
1543
1544 /// <summary>
1545 /// Lists all available display resolutions for the primary monitor.
1546 /// </summary>
1547 static void ListDisplayResolutions()
1548 {
1549 try
1550 {
1551 var resolutions = new List<object>();
1552 DEVMODE devMode = new DEVMODE();
1553 devMode.dmSize = (ushort)Marshal.SizeOf(typeof(DEVMODE));
1554
1555 int modeNum = 0;
1556 while (EnumDisplaySettings(null, modeNum, ref devMode))
1557 {
1558 resolutions.Add(new
1559 {
1560 Width = devMode.dmPelsWidth,
1561 Height = devMode.dmPelsHeight,
1562 BitsPerPixel = devMode.dmBitsPerPel,
1563 RefreshRate = devMode.dmDisplayFrequency
1564 });
1565 modeNum++;
1566 }
1567
1568 // Remove duplicates and sort by resolution
1569 var uniqueResolutions = resolutions
1570 .GroupBy(r => new { ((dynamic)r).Width, ((dynamic)r).Height, ((dynamic)r).RefreshRate })
1571 .Select(g => g.First())
1572 .OrderByDescending(r => ((dynamic)r).Width)
1573 .ThenByDescending(r => ((dynamic)r).Height)
1574 .ThenByDescending(r => ((dynamic)r).RefreshRate)
1575 .ToList();
1576
1577 Console.WriteLine(JsonConvert.SerializeObject(uniqueResolutions));
1578 }
1579 catch (Exception ex)
1580 {
1581 LogError(ex);
1582 }
1583 }
1584
1585 /// <summary>
1586 /// Sets the display resolution.
1587 /// </summary>
1588 /// <param name="value">JSON object with "width" and "height" properties, or a string like "1920x1080".</param>
1589 static void SetDisplayResolution(JToken value)
1590 {
1591 try
1592 {
1593 uint width;
1594 uint height;
1595 uint? refreshRate = null;
1596
1597 // Parse the input - can be JSON object or string like "1920x1080"
1598 if (value.Type == JTokenType.Object)
1599 {
1600 width = value.Value<uint>("width");
1601 height = value.Value<uint>("height");
1602 if (value["refreshRate"] != null)
1603 {
1604 refreshRate = value.Value<uint>("refreshRate");
1605 }
1606 }
1607 else
1608 {
1609 string resString = value.ToString();
1610 string[] parts = resString.ToLowerInvariant().Split('x', '@');
1611 if (parts.Length < 2)
1612 {
1613 LogWarning("Invalid resolution format. Use 'WIDTHxHEIGHT' or 'WIDTHxHEIGHT@REFRESH' (e.g., '1920x1080' or '1920x1080@60')");
1614 return;
1615 }
1616
1617 if (!uint.TryParse(parts[0].Trim(), out width) || !uint.TryParse(parts[1].Trim(), out height))
1618 {
1619 LogWarning("Invalid resolution values. Width and height must be positive integers.");
1620 return;
1621 }
1622
1623 if (parts.Length >= 3 && uint.TryParse(parts[2].Trim(), out uint parsedRefresh))
1624 {
1625 refreshRate = parsedRefresh;
1626 }
1627 }
1628
1629 // Get the current display settings
1630 DEVMODE currentMode = new DEVMODE();
1631 currentMode.dmSize = (ushort)Marshal.SizeOf(typeof(DEVMODE));
1632
1633 if (!EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref currentMode))
1634 {
1635 LogWarning("Failed to get current display settings.");
1636 return;
1637 }
1638
1639 // Find a matching display mode
1640 DEVMODE newMode = new DEVMODE();
1641 newMode.dmSize = (ushort)Marshal.SizeOf(typeof(DEVMODE));
1642
1643 int modeNum = 0;
1644 bool found = false;
1645 DEVMODE bestMatch = new DEVMODE();
1646
1647 while (EnumDisplaySettings(null, modeNum, ref newMode))
1648 {
1649 if (newMode.dmPelsWidth == width && newMode.dmPelsHeight == height)
1650 {
1651 if (refreshRate.HasValue)
1652 {
1653 if (newMode.dmDisplayFrequency == refreshRate.Value)
1654 {
1655 bestMatch = newMode;
1656 found = true;
1657 break;
1658 }
1659 }
1660 else
1661 {
1662 // Prefer higher refresh rate if not specified
1663 if (!found || newMode.dmDisplayFrequency > bestMatch.dmDisplayFrequency)
1664 {
1665 bestMatch = newMode;
1666 found = true;
1667 }
1668 }
1669 }
1670 modeNum++;
1671 }
1672
1673 if (!found)
1674 {
1675 LogWarning($"Resolution {width}x{height}" + (refreshRate.HasValue ? $"@{refreshRate}Hz" : "") + " is not supported.");
1676 return;
1677 }
1678
1679 // Set the required fields
1680 bestMatch.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY;
1681
1682 // TODO: better handle return value from change mode
1683 // Test if the mode change will work
1684 int testResult = ChangeDisplaySettings(ref bestMatch, CDS_TEST);
1685 if (testResult != DISP_CHANGE_SUCCESSFUL && testResult != -2)
1686 {
1687 LogWarning($"Display mode test failed with code: {testResult}");
1688 return;
1689 }
1690
1691 // Apply the change
1692 int result = ChangeDisplaySettings(ref bestMatch, CDS_UPDATEREGISTRY);
1693 switch (result)
1694 {
1695 case DISP_CHANGE_SUCCESSFUL:
1696 Console.WriteLine($"Resolution changed to {bestMatch.dmPelsWidth}x{bestMatch.dmPelsHeight}@{bestMatch.dmDisplayFrequency}Hz");
1697 break;
1698 case DISP_CHANGE_RESTART:
1699 Console.WriteLine($"Resolution will change to {bestMatch.dmPelsWidth}x{bestMatch.dmPelsHeight} after restart.");
1700 break;
1701 default:
1702 LogWarning($"Failed to change resolution. Error code: {result}");
1703 break;
1704 }
1705 }
1706 catch (Exception ex)
1707 {
1708 LogError(ex);
1709 }
1710 }
1711
1712 static void DisconnectFromWifi()
1713 {
1714 IntPtr clientHandle = IntPtr.Zero;
1715 IntPtr wlanInterfaceList = IntPtr.Zero;
1716
1717 try
1718 {
1719 // Open WLAN handle
1720 int result = WlanOpenHandle(2, IntPtr.Zero, out uint negotiatedVersion, out clientHandle);
1721 if (result != 0)
1722 {
1723 LogWarning($"Failed to open WLAN handle: {result}");
1724 return;
1725 }
1726
1727 // Enumerate wireless interfaces
1728 result = WlanEnumInterfaces(clientHandle, IntPtr.Zero, out wlanInterfaceList);
1729 if (result != 0)
1730 {
1731 LogWarning($"Failed to enumerate WLAN interfaces: {result}");
1732 return;
1733 }
1734
1735 WLAN_INTERFACE_INFO_LIST interfaceList = Marshal.PtrToStructure<WLAN_INTERFACE_INFO_LIST>(wlanInterfaceList);
1736
1737 if (interfaceList.dwNumberOfItems == 0)
1738 {
1739 LogWarning("No wireless interfaces found.");
1740 return;
1741 }
1742
1743 // Disconnect from all wireless interfaces
1744 for (int i = 0; i < interfaceList.dwNumberOfItems; i++)
1745 {
1746 WLAN_INTERFACE_INFO interfaceInfo = interfaceList.InterfaceInfo[i];
1747
1748 result = WlanDisconnect(clientHandle, ref interfaceInfo.InterfaceGuid, IntPtr.Zero);
1749 if (result != 0)
1750 {
1751 LogWarning($"Failed to disconnect from WiFi on interface {i}: {result}");
1752 }
1753 else
1754 {
1755 Debug.WriteLine($"Successfully disconnected from WiFi on interface: {interfaceInfo.strInterfaceDescription}");
1756 Console.WriteLine("Disconnected from WiFi");
1757 }
1758 }
1759 }
1760 catch (Exception ex)
1761 {
1762 LogError(ex);
1763 }
1764 finally
1765 {
1766 if (wlanInterfaceList != IntPtr.Zero)
1767 WlanFreeMemory(wlanInterfaceList);
1768 if (clientHandle != IntPtr.Zero)
1769 WlanCloseHandle(clientHandle, IntPtr.Zero);
1770 }
1771 }
1772}
1773