microsoft/TypeAgent

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
bc56e36bf67805e8fc6a22488ac05abbbde06bda

Branches

Tags

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

Clone

HTTPS

Download ZIP

dotnet/autoShell/AutoShell.cs

1358lines · 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.Linq;
10using System.Reflection;
11using System.Runtime.InteropServices;
12using System.Text;
13using System.Threading.Tasks;
14using System.Windows.Controls;
15using Microsoft.VisualBasic;
16using Microsoft.WindowsAPICodePack.Shell;
17using Newtonsoft.Json;
18using Newtonsoft.Json.Linq;
19using static autoShell.AutoShell;
20
21
22namespace autoShell;
23
24internal partial class AutoShell
25{
26 // create a map of friendly names to executable paths
27 static Hashtable s_friendlyNameToPath = [];
28 static Hashtable s_friendlyNameToId = [];
29 static double s_savedVolumePct = 0.0;
30
31 static IServiceProvider10 s_shell;
32 static IVirtualDesktopManager s_virtualDesktopManager;
33 static IVirtualDesktopManagerInternal s_virtualDesktopManagerInternal;
34 static IVirtualDesktopManagerInternal_BUGBUG s_virtualDesktopManagerInternal_BUGBUG;
35 static IApplicationViewCollection s_applicationViewCollection;
36 static IVirtualDesktopPinnedApps s_virtualDesktopPinnedApps;
37
38
39 /// <summary>
40 /// Constructor used to get system wide information required for specific commands.
41 /// </summary>
42 static AutoShell()
43 {
44 // get current user name
45 string userName = Environment.UserName;
46 SortedList<string, string> sortedList = new SortedList<string, string>
47 {
48 { "chrome", "chrome.exe" },
49 { "power point", "C:\\Program Files\\Microsoft Office\\root\\Office16\\POWERPNT.EXE" },
50 { "powerpoint", "C:\\Program Files\\Microsoft Office\\root\\Office16\\POWERPNT.EXE" },
51 { "word", "C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE" },
52 { "winword", "C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE" },
53 { "excel", "C:\\Program Files\\Microsoft Office\\root\\Office16\\EXCEL.EXE" },
54 { "outlook", "C:\\Program Files\\Microsoft Office\\root\\Office16\\OUTLOOK.EXE" },
55 { "visual studio", "devenv.exe" },
56 { "visual studio code", "C:\\Users\\" + userName + "\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe" },
57 { "edge", "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" },
58 { "microsoft edge", "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" },
59 { "notepad", "C:\\Windows\\System32\\notepad.exe" },
60 { "paint", "mspaint.exe" },
61 { "calculator", "calc.exe" },
62 { "file explorer", "C:\\Windows\\explorer.exe" },
63 { "control panel", "C:\\Windows\\System32\\control.exe" },
64 { "task manager", "C:\\Windows\\System32\\Taskmgr.exe" },
65 { "cmd", "C:\\Windows\\System32\\cmd.exe" },
66 { "powershell", "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" },
67 { "snipping tool", "C:\\Windows\\System32\\SnippingTool.exe" },
68 { "magnifier", "C:\\Windows\\System32\\Magnify.exe" },
69 { "paint 3d", "C:\\Program Files\\WindowsApps\\Microsoft.MSPaint_10.1807.18022.0_x64__8wekyb3d8bbwe\\"},
70 { "m365 copilot", "C:\\Program Files\\WindowsApps\\Microsoft.MicrosoftOfficeHub_19.2512.45041.0_x64__8wekyb3d8bbwe\\M365Copilot.exe" },
71 { "copilot", "C:\\Program Files\\WindowsApps\\Microsoft.MicrosoftOfficeHub_19.2512.45041.0_x64__8wekyb3d8bbwe\\M365Copilot.exe" },
72 { "spotify", "C:\\Program Files\\WindowsApps\\SpotifyAB.SpotifyMusic_1.279.427.0_x64__zpdnekdrzrea0\\spotify.exe" },
73 };
74
75 // add the entries to the hashtable
76 foreach (var kvp in sortedList)
77 {
78 s_friendlyNameToPath.Add(kvp.Key, kvp.Value);
79 }
80
81 var installedApps = GetAllInstalledAppsIds();
82 foreach (var kvp in installedApps)
83 {
84 s_friendlyNameToId.Add(kvp.Key, kvp.Value);
85 }
86
87 // Load the installed themes
88 LoadThemes();
89
90 // Desktop management
91 s_shell = (IServiceProvider10)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_ImmersiveShell));
92 s_virtualDesktopManagerInternal = (IVirtualDesktopManagerInternal)s_shell.QueryService(CLSID_VirtualDesktopManagerInternal, typeof(IVirtualDesktopManagerInternal).GUID);
93 s_virtualDesktopManagerInternal_BUGBUG = (IVirtualDesktopManagerInternal_BUGBUG)s_shell.QueryService(CLSID_VirtualDesktopManagerInternal, typeof(IVirtualDesktopManagerInternal).GUID);
94 s_virtualDesktopManager = (IVirtualDesktopManager)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_VirtualDesktopManager));
95 s_applicationViewCollection = (IApplicationViewCollection)s_shell.QueryService(typeof(IApplicationViewCollection).GUID, typeof(IApplicationViewCollection).GUID);
96 s_virtualDesktopPinnedApps = (IVirtualDesktopPinnedApps)s_shell.QueryService(CLSID_VirtualDesktopPinnedApps, typeof(IVirtualDesktopPinnedApps).GUID);
97 }
98
99 /// <summary>
100 /// Program entry point
101 /// </summary>
102 /// <param name="args">Any command line arguments</param>
103 static void Main(string[] args)
104 {
105 string rawCmdLine = Marshal.PtrToStringUni(GetCommandLineW());
106
107 // if there are command line args let's execute those one at a time and then exit
108 // user can specify a single JSON object command or an array of them on the command line
109 if (args.Length > 0)
110 {
111 string exe = $"\"{Environment.ProcessPath}\"";
112 string cmdLine = rawCmdLine.Replace(exe, "");
113
114 if (cmdLine.StartsWith(exe, StringComparison.OrdinalIgnoreCase))
115 {
116 cmdLine = cmdLine[exe.Length..];
117 }
118 else if (cmdLine.StartsWith(Path.GetFileName(Environment.ProcessPath), StringComparison.OrdinalIgnoreCase))
119 {
120 cmdLine = cmdLine[Path.GetFileName(Environment.ProcessPath).Length..];
121 }
122 else if (cmdLine.StartsWith(Path.GetFileNameWithoutExtension(Environment.ProcessPath), StringComparison.OrdinalIgnoreCase))
123 {
124 cmdLine = cmdLine[Path.GetFileNameWithoutExtension(Environment.ProcessPath).Length..];
125 }
126
127 try
128 {
129 JArray commands = JArray.Parse(cmdLine);
130 foreach (JObject jo in commands.Children<JObject>())
131 {
132 execLine(jo);
133 }
134 }
135 catch (JsonReaderException)
136 {
137 execLine(JObject.Parse(cmdLine));
138 }
139
140 // exit
141 return;
142 }
143
144 // run in interactive mode, keep accepting commands until we get the shutdown command
145 bool quit = false;
146 while (!quit)
147 {
148 try
149 {
150 // read a line from the console
151 string line = Console.ReadLine();
152
153 // if stdin is closed (e.g., piped input finished), exit
154 if (line == null)
155 {
156 break;
157 }
158
159 // parse the line as a json object with one or more command keys (with values as parameters)
160 JObject root = JObject.Parse(line);
161
162 // execute the line
163 quit = execLine(root);
164 }
165 catch (Exception ex)
166 {
167 LogError(ex);
168 }
169 }
170 }
171
172 static void LogError(Exception ex)
173 {
174 Debug.WriteLine(ex);
175 ConsoleColor previousColor = Console.ForegroundColor;
176 Console.ForegroundColor = ConsoleColor.Red;
177 Console.WriteLine("Error: " + ex.Message);
178 Console.ForegroundColor = previousColor;
179 }
180
181 static void LogWarning(string message)
182 {
183 Debug.WriteLine(message);
184 ConsoleColor previousColor = Console.ForegroundColor;
185 Console.ForegroundColor = ConsoleColor.Yellow;
186 Console.WriteLine("Warning: " + message);
187 Console.ForegroundColor = previousColor;
188 }
189
190 static SortedList<string, string> GetAllInstalledAppsIds()
191 {
192 // GUID taken from https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid
193 var FOLDERID_AppsFolder = new Guid("{1e87508d-89c2-42f0-8a7e-645a0f50ca58}");
194 ShellObject appsFolder = (ShellObject)KnownFolderHelper.FromKnownFolderId(FOLDERID_AppsFolder);
195 var appIds = new SortedList<string, string>();
196
197 foreach (var app in (IKnownFolder)appsFolder)
198 {
199 string appName = app.Name.ToLowerInvariant();
200 if (appIds.ContainsKey(appName))
201 {
202 Debug.WriteLine("Key has multiple values: " + appName);
203 }
204 else
205 {
206 // The ParsingName property is the AppUserModelID
207 appIds.Add(appName, app.ParsingName);
208 }
209 }
210
211 return appIds;
212 }
213
214 static void SetMasterVolume(int pct)
215 {
216 // Using Windows Core Audio API via COM interop
217 try
218 {
219 var deviceEnumerator = (IMMDeviceEnumerator)new MMDeviceEnumerator();
220 deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out IMMDevice device);
221 var audioEndpointVolumeGuid = typeof(IAudioEndpointVolume).GUID;
222 device.Activate(ref audioEndpointVolumeGuid, 0, IntPtr.Zero, out object obj);
223 var audioEndpointVolume = (IAudioEndpointVolume)obj;
224 audioEndpointVolume.GetMasterVolumeLevelScalar(out float currentVolume);
225 s_savedVolumePct = currentVolume * 100.0;
226 audioEndpointVolume.SetMasterVolumeLevelScalar(pct / 100.0f, Guid.Empty);
227 }
228 catch (Exception ex)
229 {
230 Debug.WriteLine("Failed to set volume: " + ex.Message);
231 }
232 }
233
234 static void RestoreMasterVolume()
235 {
236 // Using Windows Core Audio API via COM interop
237 try
238 {
239 var deviceEnumerator = (IMMDeviceEnumerator)new MMDeviceEnumerator();
240 deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out IMMDevice device);
241 var audioEndpointVolumeGuid = typeof(IAudioEndpointVolume).GUID;
242 device.Activate(ref audioEndpointVolumeGuid, 0, IntPtr.Zero, out object obj);
243 var audioEndpointVolume = (IAudioEndpointVolume)obj;
244 audioEndpointVolume.SetMasterVolumeLevelScalar((float)(s_savedVolumePct / 100.0), Guid.Empty);
245 }
246 catch (Exception ex)
247 {
248 Debug.WriteLine("Failed to restore volume: " + ex.Message);
249 }
250 }
251
252 static void SetMasterMute(bool mute)
253 {
254 // Using Windows Core Audio API via COM interop
255 try
256 {
257 var deviceEnumerator = (IMMDeviceEnumerator)new MMDeviceEnumerator();
258 deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia, out IMMDevice device);
259 var audioEndpointVolumeGuid = typeof(IAudioEndpointVolume).GUID;
260 device.Activate(ref audioEndpointVolumeGuid, 0, IntPtr.Zero, out object obj);
261 var audioEndpointVolume = (IAudioEndpointVolume)obj;
262 audioEndpointVolume.GetMute(out bool currentMute);
263 Debug.WriteLine("Current Mute:" + currentMute);
264 audioEndpointVolume.SetMute(mute, Guid.Empty);
265 }
266 catch (Exception ex)
267 {
268 Debug.WriteLine("Failed to set mute: " + ex.Message);
269 }
270 }
271
272 static string ResolveProcessNameFromFriendlyName(string friendlyName)
273 {
274 string path = (string)s_friendlyNameToPath[friendlyName.ToLowerInvariant()];
275 if (path != null)
276 {
277 return Path.GetFileNameWithoutExtension(path);
278 }
279 else
280 {
281 return friendlyName;
282 }
283 }
284
285 static IntPtr FindProcessWindowHandle(string processName)
286 {
287 processName = ResolveProcessNameFromFriendlyName(processName);
288 Process[] processes = Process.GetProcessesByName(processName);
289 // loop through the processes that match the name; raise the first one that has a main window
290 foreach (Process p in processes)
291 {
292 if (p.MainWindowHandle != IntPtr.Zero)
293 {
294 return p.MainWindowHandle;
295 }
296 }
297
298 // Try to find by window title if we haven't found it and bring it forward
299 return FindWindowByTitle(processName).hWnd;
300 }
301
302 // given part of a process name, raise the window of that process to the top level
303 static void RaiseWindow(string processName)
304 {
305 processName = ResolveProcessNameFromFriendlyName(processName);
306 Process[] processes = Process.GetProcessesByName(processName);
307 // loop through the processes that match the name; raise the first one that has a main window
308 foreach (Process p in processes)
309 {
310 if (p.MainWindowHandle != IntPtr.Zero)
311 {
312 SetForegroundWindow(p.MainWindowHandle);
313 Interaction.AppActivate(p.Id);
314 return;
315 }
316 }
317
318 // this means all the applications processes are running in the background. This happens for edge and chrome browsers.
319 string path = (string)s_friendlyNameToPath[processName];
320 if (path != null)
321 {
322 Process.Start(path);
323 }
324 else
325 {
326 // Try to find by window title if we haven't found it and bring it forward
327 (nint hWnd1, int pid) = FindWindowByTitle(processName);
328
329 if (hWnd1 != nint.Zero)
330 {
331 SetForegroundWindow(hWnd1);
332 Interaction.AppActivate(pid);
333 }
334 }
335 }
336
337 static void MaximizeWindow(string processName)
338 {
339 processName = ResolveProcessNameFromFriendlyName(processName);
340 Process[] processes = Process.GetProcessesByName(processName);
341 // loop through the processes that match the name; raise the first one that has a main window
342 foreach (Process p in processes)
343 {
344 if (p.MainWindowHandle != IntPtr.Zero)
345 {
346 uint WM_SYSCOMMAND = 0x112;
347 uint SC_MAXIMIZE = 0xf030;
348 SendMessage(p.MainWindowHandle, WM_SYSCOMMAND, SC_MAXIMIZE, IntPtr.Zero);
349 SetForegroundWindow(p.MainWindowHandle);
350 Interaction.AppActivate(p.Id);
351 return;
352 }
353 }
354
355 // if we haven't found what we are looking for let's enumerate the top level windows and try that way
356 (nint hWnd, int pid) = FindWindowByTitle(processName);
357 if (hWnd != nint.Zero)
358 {
359 uint WM_SYSCOMMAND = 0x112;
360 uint SC_MAXIMIZE = 0xf030;
361 SendMessage(hWnd, WM_SYSCOMMAND, SC_MAXIMIZE, IntPtr.Zero);
362 SetForegroundWindow(hWnd);
363 Interaction.AppActivate(pid);
364 }
365 }
366
367 static void MinimizeWindow(string processName)
368 {
369 processName = ResolveProcessNameFromFriendlyName(processName);
370 Process[] processes = Process.GetProcessesByName(processName);
371 // loop through the processes that match the name; raise the first one that has a main window
372 foreach (Process p in processes)
373 {
374 if (p.MainWindowHandle != IntPtr.Zero)
375 {
376 uint WM_SYSCOMMAND = 0x112;
377 uint SC_MINIMIZE = 0xF020;
378 SendMessage(p.MainWindowHandle, WM_SYSCOMMAND, SC_MINIMIZE, IntPtr.Zero);
379 break;
380 }
381 }
382
383 // if we haven't found what we are looking for let's enumerate the top level windows and try that way
384 (nint hWnd, int pid) = FindWindowByTitle(processName);
385 if (hWnd != nint.Zero)
386 {
387 uint WM_SYSCOMMAND = 0x112;
388 uint SC_MINIMIZE = 0xF020;
389 SendMessage(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, IntPtr.Zero);
390 SetForegroundWindow(hWnd);
391 Interaction.AppActivate(pid);
392 }
393 }
394
395 static void TileWindowPair(string processName1, string processName2)
396 {
397 // find both processes
398 // TODO: Update this to account for UWP apps (e.g. calculator). UWPs are hosted by ApplicationFrameHost.exe
399 processName1 = ResolveProcessNameFromFriendlyName(processName1);
400 Process[] processes1 = Process.GetProcessesByName(processName1);
401 IntPtr hWnd1 = IntPtr.Zero;
402 IntPtr hWnd2 = IntPtr.Zero;
403 int pid1 = -1;
404 int pid2 = -1;
405
406 foreach (Process p in processes1)
407 {
408 if (p.MainWindowHandle != IntPtr.Zero)
409 {
410 hWnd1 = p.MainWindowHandle;
411 pid1 = p.Id;
412 break;
413 }
414 }
415
416 // If no process found by name, search by window title
417 if (hWnd1 == IntPtr.Zero)
418 {
419 (hWnd1, pid1) = FindWindowByTitle(processName1);
420 }
421
422 processName2 = ResolveProcessNameFromFriendlyName(processName2);
423 Process[] processes2 = Process.GetProcessesByName(processName2);
424 foreach (Process p in processes2)
425 {
426 if (p.MainWindowHandle != IntPtr.Zero)
427 {
428 hWnd2 = p.MainWindowHandle;
429 pid2 = p.Id;
430 break;
431 }
432 }
433
434 // If no process found by name, search by window title
435 if (hWnd2 == IntPtr.Zero)
436 {
437 (hWnd2, pid2) = FindWindowByTitle(processName2);
438 }
439
440 if (hWnd1 != IntPtr.Zero && hWnd2 != IntPtr.Zero)
441 {
442 // TODO: handle multiple monitors
443 // get the screen size
444 IntPtr desktopHandle = GetDesktopWindow();
445 RECT desktopRect = new RECT();
446 GetWindowRect(desktopHandle, ref desktopRect);
447 // get the dimensions of the taskbar
448 // find the taskbar window
449 IntPtr taskbarHandle = IntPtr.Zero;
450 IntPtr hWnd = IntPtr.Zero;
451 while ((hWnd = FindWindowEx(IntPtr.Zero, hWnd, "Shell_TrayWnd", null)) != IntPtr.Zero)
452 {
453 // find the taskbar window's child
454 taskbarHandle = FindWindowEx(hWnd, IntPtr.Zero, "ReBarWindow32", null);
455 if (taskbarHandle != IntPtr.Zero)
456 {
457 break;
458 }
459 }
460 if (hWnd == IntPtr.Zero)
461 {
462 Debug.WriteLine("Taskbar not found");
463 return;
464 }
465 else
466 {
467 RECT taskbarRect = new RECT();
468 GetWindowRect(hWnd, ref taskbarRect);
469 Debug.WriteLine("Taskbar Rect: " + taskbarRect.Left + ", " + taskbarRect.Top + ", " + taskbarRect.Right + ", " + taskbarRect.Bottom);
470 // TODO: handle left, top, right and nonexistant taskbars
471 // subtract the taskbar height from the screen height
472 desktopRect.Bottom -= (int)((taskbarRect.Bottom - taskbarRect.Top) / 2);
473 }
474 // set the window positions using the shellRect and making sure the windows are visible
475 int halfwidth = (desktopRect.Right - desktopRect.Left) / 2;
476 IntPtr HWND_TOP = IntPtr.Zero;
477 uint showWindow = 0x40;
478 SetWindowPos(hWnd1, HWND_TOP, desktopRect.Left, desktopRect.Top, halfwidth, desktopRect.Bottom, showWindow);
479 SetForegroundWindow(hWnd1);
480 Interaction.AppActivate(pid1);
481 SetWindowPos(hWnd2, HWND_TOP, desktopRect.Left + halfwidth, desktopRect.Top, halfwidth, desktopRect.Bottom, showWindow);
482 SetForegroundWindow(hWnd2);
483 Interaction.AppActivate(pid2);
484 }
485 }
486
487 /// <summary>
488 /// Finds a top-level window by searching for a partial match in the window title.
489 /// </summary>
490 /// <param name="titleSearch">The text to search for in window titles (case-insensitive).</param>
491 /// <returns>A tuple containing the window handle and process ID, or (IntPtr.Zero, -1) if not found.</returns>
492 static (IntPtr hWnd, int pid) FindWindowByTitle(string titleSearch)
493 {
494 IntPtr foundHandle = IntPtr.Zero;
495 int foundPid = -1;
496 StringBuilder windowTitle = new StringBuilder(256);
497
498 EnumWindows((hWnd, lParam) =>
499 {
500 // Only consider visible windows
501 if (!IsWindowVisible(hWnd))
502 {
503 return true; // Continue enumeration
504 }
505
506 // Get window title
507 int length = GetWindowText(hWnd, windowTitle, windowTitle.Capacity);
508 if (length > 0)
509 {
510 string title = windowTitle.ToString();
511 // Case-insensitive partial match
512 if (title.Contains(titleSearch, StringComparison.OrdinalIgnoreCase))
513 {
514 foundHandle = hWnd;
515 GetWindowThreadProcessId(hWnd, out uint pid);
516 foundPid = (int)pid;
517 return false; // Stop enumeration
518 }
519 }
520 return true; // Continue enumeration
521 }, IntPtr.Zero);
522
523 return (foundHandle, foundPid);
524 }
525
526 // given a friendly name, check if it's running and if not, start it; if it's running raise it to the top level
527 static void OpenApplication(string friendlyName)
528 {
529 // check to see if the application is running
530 Process[] processes = Process.GetProcessesByName(friendlyName);
531 if (processes.Length == 0)
532 {
533 // if not, start it
534 Debug.WriteLine("Starting " + friendlyName);
535 string path = (string)s_friendlyNameToPath[friendlyName.ToLowerInvariant()];
536 if (path != null)
537 {
538 try
539 {
540 Process.Start(path);
541 }
542 catch (System.ComponentModel.Win32Exception)
543 {
544 // alternate start method
545 Process.Start(friendlyName);
546 }
547 }
548 else
549 {
550 string appModelUserID = (string)s_friendlyNameToId[friendlyName.ToLowerInvariant()];
551 if (appModelUserID != null)
552 {
553 try
554 {
555 Process.Start("explorer.exe", @" shell:appsFolder\" + appModelUserID);
556 }
557 catch { }
558 }
559 }
560 }
561 else
562 {
563 // if so, raise it to the top level
564 Debug.WriteLine("Raising " + friendlyName);
565 RaiseWindow(friendlyName);
566 }
567 }
568
569 // close application
570 static void CloseApplication(string friendlyName)
571 {
572 // check to see if the application is running
573 string processName = ResolveProcessNameFromFriendlyName(friendlyName);
574 Process[] processes = Process.GetProcessesByName(processName);
575 if (processes.Length != 0)
576 {
577 // if so, close it
578 Debug.WriteLine("Closing " + friendlyName);
579 foreach (Process p in processes)
580 {
581 if (p.MainWindowHandle != IntPtr.Zero)
582 {
583 p.CloseMainWindow();
584 }
585 }
586 }
587 }
588
589 private static void SetDesktopWallpaper(string imagePath)
590 {
591 SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, imagePath, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
592 }
593
594 /// <summary>
595 /// Creates virtual desktops from a JSON array of desktop names.
596 /// </summary>
597 /// <param name="jsonValue">JSON array containing desktop names, e.g., ["Work", "Personal", "Gaming"]</param>
598 static void CreateDesktop(string jsonValue)
599 {
600 try
601 {
602 // Parse the JSON array of desktop names
603 JArray desktopNames = JArray.Parse(jsonValue);
604
605 if (desktopNames == null || desktopNames.Count == 0)
606 {
607 Debug.WriteLine("No desktop names provided");
608 return;
609 }
610
611 if (s_virtualDesktopManagerInternal == null)
612 {
613 Debug.WriteLine($"Failed to get Virtual Desktop Manager Internal");
614 return;
615 }
616
617 foreach (JToken desktopNameToken in desktopNames)
618 {
619 string desktopName = desktopNameToken.ToString();
620
621 if (string.IsNullOrWhiteSpace(desktopName))
622 {
623 continue;
624 }
625
626 try
627 {
628 // Create a new virtual desktop
629 IVirtualDesktop newDesktop = s_virtualDesktopManagerInternal.CreateDesktop();
630
631 if (newDesktop != null)
632 {
633 // Set the desktop name (Windows 10 build 20231+ / Windows 11)
634 try
635 {
636 // TODO: debug & get working
637 // Works in .NET framework but not .NET
638 //s_virtualDesktopManagerInternal_BUGBUG.SetDesktopName(newDesktop, desktopName);
639 //Debug.WriteLine($"Created virtual desktop: {desktopName}");
640 }
641 catch (Exception ex2)
642 {
643 // Older Windows version - name setting not supported
644 Debug.WriteLine($"Created virtual desktop (naming not supported on this Windows version): {ex2.Message}");
645 }
646 }
647 }
648 catch (Exception ex)
649 {
650 Debug.WriteLine($"Failed to create desktop '{desktopName}': {ex.Message}");
651 }
652 }
653 }
654 catch (JsonException ex)
655 {
656 Debug.WriteLine($"Failed to parse desktop names JSON: {ex.Message}");
657 }
658 catch (Exception ex)
659 {
660 Debug.WriteLine($"Error creating desktops: {ex.Message}");
661 }
662 }
663
664 static void SwitchDesktop(string desktopIdentifier)
665 {
666 if (!int.TryParse(desktopIdentifier, out int index))
667 {
668 // Try to find the desktop by name
669 s_virtualDesktopManagerInternal.SwitchDesktop(FindDesktopByName(desktopIdentifier));
670 }
671 else
672 {
673 SwitchDesktop(index);
674 }
675 }
676
677 static void SwitchDesktop(int index)
678 {
679 s_virtualDesktopManagerInternal.GetDesktops(out IObjectArray desktops);
680 desktops.GetAt(index, typeof(IVirtualDesktop).GUID, out object od);
681
682 // BUGBUG: different windows versions use different COM interfaces
683 // Different Windows versions use different COM interfaces for desktop switching
684 // Windows 11 22H2 (build 22621) and later use the updated interface
685 if (OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22621))
686 {
687 // Use the BUGBUG interface for Windows 11 22H2+
688 s_virtualDesktopManagerInternal_BUGBUG.SwitchDesktopWithAnimation((IVirtualDesktop)od);
689 }
690 else if (OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22000))
691 {
692 // Windows 11 21H2 (build 22000)
693 s_virtualDesktopManagerInternal.SwitchDesktopWithAnimation((IVirtualDesktop)od);
694 }
695 else
696 {
697 // Windows 10 - use the original interface
698 s_virtualDesktopManagerInternal.SwitchDesktopAndMoveForegroundView((IVirtualDesktop)od);
699 }
700
701 Marshal.ReleaseComObject(desktops);
702 }
703
704 static void BumpDesktopIndex(int bump)
705 {
706 IVirtualDesktop desktop = s_virtualDesktopManagerInternal.GetCurrentDesktop();
707 int index = GetDesktopIndex(desktop);
708 int count = s_virtualDesktopManagerInternal.GetCount();
709
710 if (index == -1)
711 {
712 Debug.WriteLine("Undable to get the index of the current desktop");
713 return;
714 }
715
716 index += bump;
717
718 if (index > count)
719 {
720 index = 0;
721 }
722 else if (index < 0)
723 {
724 index = count - 1;
725 }
726
727 SwitchDesktop(index);
728 }
729
730 static IVirtualDesktop FindDesktopByName(string name)
731 {
732 int count = s_virtualDesktopManagerInternal.GetCount();
733
734 s_virtualDesktopManagerInternal.GetDesktops(out IObjectArray desktops);
735 for (int i = 0; i < count; i++)
736 {
737 desktops.GetAt(i, typeof(IVirtualDesktop).GUID, out object od);
738
739 if (string.Equals(((IVirtualDesktop)od).GetName(), name, StringComparison.OrdinalIgnoreCase))
740 {
741 Marshal.ReleaseComObject(desktops);
742 return (IVirtualDesktop)od;
743 }
744 }
745
746 Marshal.ReleaseComObject(desktops);
747
748 return null;
749 }
750
751 static int GetDesktopIndex(IVirtualDesktop desktop)
752 {
753 int index = -1;
754 int count = s_virtualDesktopManagerInternal.GetCount();
755
756 s_virtualDesktopManagerInternal.GetDesktops(out IObjectArray desktops);
757 for (int i = 0; i < count; i++)
758 {
759 desktops.GetAt(i, typeof(IVirtualDesktop).GUID, out object od);
760
761 if (desktop.GetId() == ((IVirtualDesktop)od).GetId())
762 {
763 Marshal.ReleaseComObject(desktops);
764 return i;
765 }
766 }
767
768 Marshal.ReleaseComObject(desktops);
769
770 return -1;
771 }
772
773 /// <summary>
774 ///
775 /// </summary>
776 /// <param name="value"></param>
777 /// <remarks>Currently not working correction, returns ACCESS_DENIED // TODO: investigate</remarks>
778 static void MoveWindowToDesktop(JToken value)
779 {
780 string process = value.SelectToken("process").ToString();
781 string desktop = value.SelectToken("desktop").ToString();
782 if (string.IsNullOrEmpty(process))
783 {
784 Debug.WriteLine("No process name supplied");
785 return;
786 }
787
788 if (string.IsNullOrEmpty(desktop))
789 {
790 Debug.WriteLine("No desktop id supplied");
791 return;
792 }
793
794 IntPtr hWnd = FindProcessWindowHandle(process);
795
796 if (int.TryParse(desktop, out int desktopIndex))
797 {
798 s_virtualDesktopManagerInternal.GetDesktops(out IObjectArray desktops);
799 if (desktopIndex < 1 || desktopIndex > s_virtualDesktopManagerInternal.GetCount())
800 {
801 Debug.WriteLine("Desktop index out of range");
802 Marshal.ReleaseComObject(desktops);
803 return;
804 }
805 desktops.GetAt(desktopIndex - 1, typeof(IVirtualDesktop).GUID, out object od);
806 Guid g = ((IVirtualDesktop)od).GetId();
807 s_virtualDesktopManager.MoveWindowToDesktop(hWnd, ref g);
808 Marshal.ReleaseComObject(desktops);
809 return;
810 }
811
812 IVirtualDesktop ivd = FindDesktopByName(desktop);
813 if (ivd is not null)
814 {
815 Guid desktopGuid = ivd.GetId();
816 s_virtualDesktopManager.MoveWindowToDesktop(hWnd, ref desktopGuid);
817 }
818 }
819
820 static void PinWindow(string processName)
821 {
822 IntPtr hWnd = FindProcessWindowHandle(processName);
823
824 if (hWnd != IntPtr.Zero)
825 {
826 s_applicationViewCollection.GetViewForHwnd(hWnd, out IApplicationView view);
827
828 if (view is not null)
829 {
830 s_virtualDesktopPinnedApps.PinView((IApplicationView)view);
831 }
832 }
833 else
834 {
835 Console.WriteLine($"The window handle for '{processName}' could not be found");
836 }
837 }
838
839 static IVirtualDesktopManagerInternal GetVirtualDesktopManagerInternal()
840 {
841 try
842 {
843 IServiceProvider shellServiceProvider = (IServiceProvider)Activator.CreateInstance(
844 Type.GetTypeFromCLSID(CLSID_ImmersiveShell));
845
846 shellServiceProvider.QueryService(
847 CLSID_VirtualDesktopManagerInternal,
848 typeof(IVirtualDesktopManagerInternal).GUID,
849 out object objVirtualDesktopManagerInternal);
850
851 return (IVirtualDesktopManagerInternal)objVirtualDesktopManagerInternal;
852 }
853 catch
854 {
855 return null;
856 }
857 }
858
859 static bool execLine(JObject root)
860 {
861 var quit = false;
862 foreach (var kvp in root)
863 {
864 string key = kvp.Key;
865 string value = kvp.Value.ToString();
866 switch (key)
867 {
868 case "launchProgram":
869 OpenApplication(value);
870 break;
871 case "closeProgram":
872 CloseApplication(value);
873 break;
874 case "maximize":
875 MaximizeWindow(value);
876 break;
877 case "minimize":
878 MinimizeWindow(value);
879 break;
880 case "switchTo":
881 RaiseWindow(value);
882 break;
883 case "quit":
884 quit = true;
885 break;
886 case "tile":
887 string[] apps = value.Split(',');
888 if (apps.Length == 2)
889 {
890 TileWindowPair(apps[0], apps[1]);
891 }
892 break;
893 case "volume":
894 int pct = 0;
895 if (int.TryParse(value, out pct))
896 {
897 SetMasterVolume(pct);
898 }
899 break;
900 case "restoreVolume":
901 RestoreMasterVolume();
902 break;
903 case "mute":
904 bool mute = false;
905 if (bool.TryParse(value, out mute))
906 {
907 SetMasterMute(mute);
908 }
909 break;
910 case "listAppNames":
911 var installedApps = GetAllInstalledAppsIds();
912 Console.WriteLine(JsonConvert.SerializeObject(installedApps.Keys));
913 break;
914 case "setWallpaper":
915 SetDesktopWallpaper(value);
916 break;
917 case "applyTheme":
918 bool result = ApplyTheme(value);
919 break;
920 case "listThemes":
921 var themes = GetInstalledThemes();
922 Console.WriteLine(JsonConvert.SerializeObject(themes));
923 break;
924 case "setThemeMode":
925 // value can be "light", "dark", "toggle", or boolean
926 if (value.Equals("toggle", StringComparison.OrdinalIgnoreCase))
927 {
928 ToggleLightDarkMode();
929 }
930 else
931 {
932 bool useLightMode;
933 if (bool.TryParse(value, out useLightMode))
934 {
935 SetLightDarkMode(useLightMode);
936 }
937 else if (value.Equals("light", StringComparison.OrdinalIgnoreCase))
938 {
939 SetLightDarkMode(true);
940 }
941 else if (value.Equals("dark", StringComparison.OrdinalIgnoreCase))
942 {
943 SetLightDarkMode(false);
944 }
945 }
946 break;
947 case "createDesktop":
948 CreateDesktop(value);
949 break;
950 case "switchDesktop":
951 SwitchDesktop(value);
952 break;
953 case "nextDesktop":
954 BumpDesktopIndex(1);
955 break;
956 case "previousDesktop":
957 BumpDesktopIndex(-1);
958 break;
959 case "moveWindowToDesktop":
960 MoveWindowToDesktop(kvp.Value);
961 break;
962 case "pinWindow":
963 PinWindow(value);
964 break;
965 case "toggleNotifications":
966 ShellExecute(IntPtr.Zero, "open", "ms-actioncenter:", null, null, 1);
967 break;
968 case "debug":
969 Debugger.Launch();
970 break;
971 case "toggleAirplaneMode":
972 SetAirplaneMode(bool.Parse(value));
973 break;
974 case "listWifiNetworks":
975 ListWifiNetworks();
976 break;
977 case "connectWifi":
978 JObject netInfo = JObject.Parse(value);
979 string ssid = netInfo.Value<string>("ssid");
980 string password = netInfo["password"] is not null ? netInfo.Value<string>("password") : "";
981 ConnectToWifi(ssid, password);
982 break;
983 case "disconnectWifi":
984 DisconnectFromWifi();
985 break;
986 default:
987 Debug.WriteLine("Unknown command: " + key);
988 break;
989 }
990 }
991 return quit;
992 }
993
994 /// <summary>
995 /// Sets the airplane mode state using the Radio Management API.
996 /// </summary>
997 /// <param name="enable">True to enable airplane mode, false to disable.</param>
998 static void SetAirplaneMode(bool enable)
999 {
1000 IRadioManager radioManager = null;
1001 try
1002 {
1003 // Create the Radio Management API COM object
1004 Type radioManagerType = Type.GetTypeFromCLSID(CLSID_RadioManagementAPI);
1005 if (radioManagerType == null)
1006 {
1007 Debug.WriteLine("Failed to get Radio Management API type");
1008 return;
1009 }
1010
1011 object obj = Activator.CreateInstance(radioManagerType);
1012 radioManager = (IRadioManager)obj;
1013
1014 if (radioManager == null)
1015 {
1016 Debug.WriteLine("Failed to create Radio Manager instance");
1017 return;
1018 }
1019
1020 // Get current state (for logging)
1021 int hr = radioManager.GetSystemRadioState(out int currentState, out int _, out int _);
1022 if (hr < 0)
1023 {
1024 Debug.WriteLine($"Failed to get system radio state: HRESULT 0x{hr:X8}");
1025 return;
1026 }
1027
1028 // currentState: 0 = airplane mode ON (radios off), 1 = airplane mode OFF (radios on)
1029 bool airplaneModeCurrentlyOn = currentState == 0;
1030 Debug.WriteLine($"Current airplane mode state: {(airplaneModeCurrentlyOn ? "on" : "off")}");
1031
1032 // Set the new state
1033 // bEnabled: 0 = turn airplane mode ON (disable radios), 1 = turn airplane mode OFF (enable radios)
1034 int newState = enable ? 0 : 1;
1035 hr = radioManager.SetSystemRadioState(newState);
1036 if (hr < 0)
1037 {
1038 Debug.WriteLine($"Failed to set system radio state: HRESULT 0x{hr:X8}");
1039 return;
1040 }
1041
1042 Debug.WriteLine($"Airplane mode set to: {(enable ? "on" : "off")}");
1043 }
1044 catch (COMException ex)
1045 {
1046 Debug.WriteLine($"COM Exception setting airplane mode: {ex.Message} (HRESULT: 0x{ex.HResult:X8})");
1047 }
1048 catch (Exception ex)
1049 {
1050 Debug.WriteLine($"Failed to set airplane mode: {ex.Message}");
1051 }
1052 finally
1053 {
1054 if (radioManager != null)
1055 {
1056 Marshal.ReleaseComObject(radioManager);
1057 }
1058 }
1059 }
1060
1061 /// <summary>
1062 /// Lists all WiFi networks currently in range.
1063 /// </summary>
1064 static void ListWifiNetworks()
1065 {
1066 IntPtr clientHandle = IntPtr.Zero;
1067 IntPtr wlanInterfaceList = IntPtr.Zero;
1068 IntPtr networkList = IntPtr.Zero;
1069
1070 try
1071 {
1072 // Open WLAN handle
1073 int result = WlanOpenHandle(2, IntPtr.Zero, out uint negotiatedVersion, out clientHandle);
1074 if (result != 0)
1075 {
1076 Debug.WriteLine($"Failed to open WLAN handle: {result}");
1077 return;
1078 }
1079
1080 // Enumerate wireless interfaces
1081 result = WlanEnumInterfaces(clientHandle, IntPtr.Zero, out wlanInterfaceList);
1082 if (result != 0)
1083 {
1084 Debug.WriteLine($"Failed to enumerate WLAN interfaces: {result}");
1085 return;
1086 }
1087
1088 WLAN_INTERFACE_INFO_LIST interfaceList = Marshal.PtrToStructure<WLAN_INTERFACE_INFO_LIST>(wlanInterfaceList);
1089
1090 if (interfaceList.dwNumberOfItems == 0)
1091 {
1092 Console.WriteLine("[]");
1093 return;
1094 }
1095
1096 var allNetworks = new List<object>();
1097
1098 for (int i = 0; i < interfaceList.dwNumberOfItems; i++)
1099 {
1100 WLAN_INTERFACE_INFO interfaceInfo = interfaceList.InterfaceInfo[i];
1101
1102 // Scan for networks (trigger a refresh)
1103 WlanScan(clientHandle, ref interfaceInfo.InterfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
1104
1105 // Small delay to allow scan to complete
1106 System.Threading.Thread.Sleep(100);
1107
1108 // Get available networks
1109 result = WlanGetAvailableNetworkList(clientHandle, ref interfaceInfo.InterfaceGuid, 0, IntPtr.Zero, out networkList);
1110 if (result != 0)
1111 {
1112 Debug.WriteLine($"Failed to get network list: {result}");
1113 continue;
1114 }
1115
1116 WLAN_AVAILABLE_NETWORK_LIST availableNetworkList = Marshal.PtrToStructure<WLAN_AVAILABLE_NETWORK_LIST>(networkList);
1117
1118 IntPtr networkPtr = networkList + 8; // Skip dwNumberOfItems and dwIndex
1119
1120 for (int j = 0; j < availableNetworkList.dwNumberOfItems; j++)
1121 {
1122 WLAN_AVAILABLE_NETWORK network = Marshal.PtrToStructure<WLAN_AVAILABLE_NETWORK>(networkPtr);
1123
1124 string ssid = Encoding.ASCII.GetString(network.dot11Ssid.SSID, 0, (int)network.dot11Ssid.SSIDLength);
1125
1126 if (!string.IsNullOrEmpty(ssid))
1127 {
1128 allNetworks.Add(new
1129 {
1130 SSID = ssid,
1131 SignalQuality = network.wlanSignalQuality,
1132 Secured = network.bSecurityEnabled,
1133 Connected = (network.dwFlags & 1) != 0 // WLAN_AVAILABLE_NETWORK_CONNECTED
1134 });
1135 }
1136
1137 networkPtr += Marshal.SizeOf<WLAN_AVAILABLE_NETWORK>();
1138 }
1139
1140 if (networkList != IntPtr.Zero)
1141 {
1142 WlanFreeMemory(networkList);
1143 networkList = IntPtr.Zero;
1144 }
1145 }
1146
1147 // Remove duplicates and sort by signal strength
1148 var uniqueNetworks = allNetworks
1149 .GroupBy(n => ((dynamic)n).SSID)
1150 .Select(g => g.OrderByDescending(n => ((dynamic)n).SignalQuality).First())
1151 .OrderByDescending(n => ((dynamic)n).SignalQuality)
1152 .ToList();
1153
1154 Console.WriteLine(JsonConvert.SerializeObject(uniqueNetworks));
1155 }
1156 catch (Exception ex)
1157 {
1158 Debug.WriteLine($"Error listing WiFi networks: {ex.Message}");
1159 Console.WriteLine("[]");
1160 }
1161 finally
1162 {
1163 if (networkList != IntPtr.Zero)
1164 WlanFreeMemory(networkList);
1165 if (wlanInterfaceList != IntPtr.Zero)
1166 WlanFreeMemory(wlanInterfaceList);
1167 if (clientHandle != IntPtr.Zero)
1168 WlanCloseHandle(clientHandle, IntPtr.Zero);
1169 }
1170 }
1171
1172 /// <summary>
1173 /// Connects to a WiFi network by name (SSID). If the network requires a password and one is provided,
1174 /// it will create a temporary profile. For networks with existing profiles, it connects using the profile.
1175 /// </summary>
1176 /// <param name="ssid">The SSID of the network to connect to.</param>
1177 /// <param name="password">Optional password for secured networks.</param>
1178 static void ConnectToWifi(string ssid, string password = null)
1179 {
1180 IntPtr clientHandle = IntPtr.Zero;
1181 IntPtr wlanInterfaceList = IntPtr.Zero;
1182
1183 try
1184 {
1185 // Open WLAN handle
1186 int result = WlanOpenHandle(2, IntPtr.Zero, out uint negotiatedVersion, out clientHandle);
1187 if (result != 0)
1188 {
1189 LogWarning($"Failed to open WLAN handle: {result}");
1190 return;
1191 }
1192
1193 // Enumerate wireless interfaces
1194 result = WlanEnumInterfaces(clientHandle, IntPtr.Zero, out wlanInterfaceList);
1195 if (result != 0)
1196 {
1197 LogWarning($"Failed to enumerate WLAN interfaces: {result}");
1198 return;
1199 }
1200
1201 WLAN_INTERFACE_INFO_LIST interfaceList = Marshal.PtrToStructure<WLAN_INTERFACE_INFO_LIST>(wlanInterfaceList);
1202
1203 if (interfaceList.dwNumberOfItems == 0)
1204 {
1205 LogWarning("No wireless interfaces found.");
1206 return;
1207 }
1208
1209 // Use the first available wireless interface
1210 WLAN_INTERFACE_INFO interfaceInfo = interfaceList.InterfaceInfo[0];
1211
1212 // If password is provided, create a profile and connect
1213 if (!string.IsNullOrEmpty(password))
1214 {
1215 string profileXml = GenerateWifiProfileXml(ssid, password);
1216
1217 result = WlanSetProfile(clientHandle, ref interfaceInfo.InterfaceGuid, 0, profileXml, null, true, IntPtr.Zero, out uint reasonCode);
1218 if (result != 0)
1219 {
1220 LogWarning($"Failed to set WiFi profile: {result}, reason: {reasonCode}");
1221 return;
1222 }
1223 }
1224
1225 // Set up connection parameters
1226 WLAN_CONNECTION_PARAMETERS connectionParams = new WLAN_CONNECTION_PARAMETERS
1227 {
1228 wlanConnectionMode = WLAN_CONNECTION_MODE.wlan_connection_mode_profile,
1229 strProfile = ssid,
1230 pDot11Ssid = IntPtr.Zero,
1231 pDesiredBssidList = IntPtr.Zero,
1232 dot11BssType = DOT11_BSS_TYPE.dot11_BSS_type_any,
1233 dwFlags = 0
1234 };
1235
1236 result = WlanConnect(clientHandle, ref interfaceInfo.InterfaceGuid, ref connectionParams, IntPtr.Zero);
1237 if (result != 0)
1238 {
1239 LogWarning($"Failed to connect to WiFi network '{ssid}': {result}");
1240 return;
1241 }
1242
1243 Debug.WriteLine($"Successfully initiated connection to WiFi network: {ssid}");
1244 Console.WriteLine($"Connecting to WiFi network: {ssid}");
1245 }
1246 catch (Exception ex)
1247 {
1248 LogError(ex);
1249 }
1250 finally
1251 {
1252 if (wlanInterfaceList != IntPtr.Zero)
1253 WlanFreeMemory(wlanInterfaceList);
1254 if (clientHandle != IntPtr.Zero)
1255 WlanCloseHandle(clientHandle, IntPtr.Zero);
1256 }
1257 }
1258
1259 /// <summary>
1260 /// Generates a WiFi profile XML for WPA2-Personal (PSK) networks.
1261 /// </summary>
1262 static string GenerateWifiProfileXml(string ssid, string password)
1263 {
1264 // Convert SSID to hex
1265 string ssidHex = BitConverter.ToString(Encoding.UTF8.GetBytes(ssid)).Replace("-", "");
1266
1267 return $@"<?xml version=""1.0""?>
1268<WLANProfile xmlns=""http://www.microsoft.com/networking/WLAN/profile/v1"">
1269 <name>{ssid}</name>
1270 <SSIDConfig>
1271 <SSID>
1272 <hex>{ssidHex}</hex>
1273 <name>{ssid}</name>
1274 </SSID>
1275 </SSIDConfig>
1276 <connectionType>ESS</connectionType>
1277 <connectionMode>auto</connectionMode>
1278 <MSM>
1279 <security>
1280 <authEncryption>
1281 <authentication>WPA2PSK</authentication>
1282 <encryption>AES</encryption>
1283 <useOneX>false</useOneX>
1284 </authEncryption>
1285 <sharedKey>
1286 <keyType>passPhrase</keyType>
1287 <protected>false</protected>
1288 <keyMaterial>{password}</keyMaterial>
1289 </sharedKey>
1290 </security>
1291 </MSM>
1292</WLANProfile>";
1293 }
1294
1295 /// <summary>
1296 /// Disconnects from the currently connected WiFi network.
1297 /// </summary>
1298 static void DisconnectFromWifi()
1299 {
1300 IntPtr clientHandle = IntPtr.Zero;
1301 IntPtr wlanInterfaceList = IntPtr.Zero;
1302
1303 try
1304 {
1305 // Open WLAN handle
1306 int result = WlanOpenHandle(2, IntPtr.Zero, out uint negotiatedVersion, out clientHandle);
1307 if (result != 0)
1308 {
1309 LogWarning($"Failed to open WLAN handle: {result}");
1310 return;
1311 }
1312
1313 // Enumerate wireless interfaces
1314 result = WlanEnumInterfaces(clientHandle, IntPtr.Zero, out wlanInterfaceList);
1315 if (result != 0)
1316 {
1317 LogWarning($"Failed to enumerate WLAN interfaces: {result}");
1318 return;
1319 }
1320
1321 WLAN_INTERFACE_INFO_LIST interfaceList = Marshal.PtrToStructure<WLAN_INTERFACE_INFO_LIST>(wlanInterfaceList);
1322
1323 if (interfaceList.dwNumberOfItems == 0)
1324 {
1325 LogWarning("No wireless interfaces found.");
1326 return;
1327 }
1328
1329 // Disconnect from all wireless interfaces
1330 for (int i = 0; i < interfaceList.dwNumberOfItems; i++)
1331 {
1332 WLAN_INTERFACE_INFO interfaceInfo = interfaceList.InterfaceInfo[i];
1333
1334 result = WlanDisconnect(clientHandle, ref interfaceInfo.InterfaceGuid, IntPtr.Zero);
1335 if (result != 0)
1336 {
1337 LogWarning($"Failed to disconnect from WiFi on interface {i}: {result}");
1338 }
1339 else
1340 {
1341 Debug.WriteLine($"Successfully disconnected from WiFi on interface: {interfaceInfo.strInterfaceDescription}");
1342 Console.WriteLine("Disconnected from WiFi");
1343 }
1344 }
1345 }
1346 catch (Exception ex)
1347 {
1348 LogError(ex);
1349 }
1350 finally
1351 {
1352 if (wlanInterfaceList != IntPtr.Zero)
1353 WlanFreeMemory(wlanInterfaceList);
1354 if (clientHandle != IntPtr.Zero)
1355 WlanCloseHandle(clientHandle, IntPtr.Zero);
1356 }
1357 }
1358}
1359