|
| 1 | +// Copyright (c) Files Community |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using System.Runtime.InteropServices; |
| 5 | +using Windows.Win32; |
| 6 | +using Windows.Win32.Foundation; |
| 7 | +using Windows.Win32.System.Com; |
| 8 | +using Windows.Win32.UI.Shell; |
| 9 | + |
| 10 | +namespace Files.App.Utils.Shell |
| 11 | +{ |
| 12 | + internal static class DetectionAndSharingHelper |
| 13 | + { |
| 14 | + public static unsafe NetworkAvailability GetNetworkAvailability() |
| 15 | + { |
| 16 | + using ComPtr<IDetectionAndSharing> dtsh = CreateDetectionAndSharing(); |
| 17 | + var availability = NetworkAvailability.None; |
| 18 | + |
| 19 | + if (IsEnabled(dtsh.Get(), DTSH_TYPE.DTSH_NETWORK_DISCOVERY)) |
| 20 | + availability |= NetworkAvailability.Discovery; |
| 21 | + |
| 22 | + if (IsEnabled(dtsh.Get(), DTSH_TYPE.DTSH_FILE_SHARING)) |
| 23 | + availability |= NetworkAvailability.Sharing; |
| 24 | + |
| 25 | + return availability; |
| 26 | + } |
| 27 | + |
| 28 | + public static unsafe void OpenNetworkSharingSettings() |
| 29 | + { |
| 30 | + using ComPtr<IOpenControlPanel> controlPanel = default; |
| 31 | + HRESULT hr = controlPanel.CoCreateInstance(CLSID.CLSID_OpenControlPanel, null, CLSCTX.CLSCTX_INPROC_SERVER); |
| 32 | + ThrowIfFailed(hr, "Failed to create open control panel object."); |
| 33 | + |
| 34 | + fixed (char* name = "Microsoft.NetworkAndSharingCenter") |
| 35 | + fixed (char* page = "Advanced") |
| 36 | + { |
| 37 | + hr = controlPanel.Get()->Open(name, page, null); |
| 38 | + ThrowIfFailed(hr, "Failed to open advanced sharing settings."); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + private static unsafe ComPtr<IDetectionAndSharing> CreateDetectionAndSharing() |
| 43 | + { |
| 44 | + ComPtr<IDetectionAndSharing> dtsh = default; |
| 45 | + HRESULT hr = dtsh.CoCreateInstance(CLSID.CLSID_DetectionAndSharing, null, CLSCTX.CLSCTX_INPROC_SERVER); |
| 46 | + ThrowIfFailed(hr, "Failed to create detection and sharing object."); |
| 47 | + |
| 48 | + return dtsh; |
| 49 | + } |
| 50 | + |
| 51 | + private static unsafe bool IsEnabled(IDetectionAndSharing* dtsh, DTSH_TYPE type) |
| 52 | + { |
| 53 | + DTSH_STATE state; |
| 54 | + DTSH_ACTION action; |
| 55 | + HRESULT hr = dtsh->GetStatus(type, &state, &action); |
| 56 | + ThrowIfFailed(hr, $"Failed to get {type} status."); |
| 57 | + |
| 58 | + return state is DTSH_STATE.DTSH_ON; |
| 59 | + } |
| 60 | + |
| 61 | + private static void ThrowIfFailed(HRESULT hr, string message) |
| 62 | + { |
| 63 | + if (hr.Failed) |
| 64 | + throw new COMException(message, hr.Value); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments