Skip to content

Commit b5c1816

Browse files
authored
Code Quality: Removed Vanara.PInvoke.Mpr & Vanara.PInvoke.DwmApi (#15292)
1 parent fdc81d8 commit b5c1816

File tree

5 files changed

+132
-57
lines changed

5 files changed

+132
-57
lines changed

src/Files.App/Files.App.csproj

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,8 @@
9393
<PackageReference Include="CommunityToolkit.WinUI.UI.Controls" Version="7.1.2" />
9494
<PackageReference Include="TagLibSharp" Version="2.3.0" />
9595
<PackageReference Include="Tulpep.ActiveDirectoryObjectPicker" Version="3.0.11" />
96-
<PackageReference Include="Vanara.PInvoke.DwmApi" Version="4.0.1" />
97-
<PackageReference Include="Vanara.Windows.Extensions" Version="4.0.1" />
9896
<PackageReference Include="WinUIEx" Version="2.3.4" />
99-
<PackageReference Include="Vanara.PInvoke.Mpr" Version="4.0.1" />
97+
<PackageReference Include="Vanara.Windows.Extensions" Version="4.0.1" />
10098
<PackageReference Include="Vanara.Windows.Shell" Version="4.0.1" />
10199
<PackageReference Include="Microsoft.Management.Infrastructure" Version="3.0.0" />
102100
<PackageReference Include="Microsoft.Management.Infrastructure.Runtime.Win" Version="3.0.0" />

src/Files.App/NativeMethods.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,16 @@ DeleteFileFromApp
4646
RemoveDirectoryFromApp
4747
GetKeyState
4848
CreateDirectoryFromApp
49+
WNetCancelConnection2
50+
NET_USE_CONNECT_FLAGS
51+
NETRESOURCEW
52+
WNetAddConnection3
53+
CREDENTIALW
54+
CredWrite
55+
WNetConnectionDialog1
56+
CONNECTDLGSTRUCTW
57+
DwmSetWindowAttribute
58+
WIN32_ERROR
4959
CoCreateInstance
5060
FileOpenDialog
5161
IFileOpenDialog

src/Files.App/Services/CommonDialogService.cs

Lines changed: 46 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
using Vanara.Extensions;
88
using Windows.Win32;
99
using Windows.Win32.Foundation;
10+
using Windows.Win32.NetworkManagement.WNet;
1011
using Windows.Win32.System.Com;
1112
using Windows.Win32.UI.Shell;
1213
using Windows.Win32.UI.Shell.Common;
@@ -179,43 +180,46 @@ public bool Open_NetworkConnectionDialog(nint hWind, bool hideRestoreConnectionC
179180

180181
private sealed class NetworkConnectionDialog : CommonDialog
181182
{
182-
private readonly Vanara.PInvoke.Mpr.NETRESOURCE netRes = new();
183-
private Vanara.PInvoke.Mpr.CONNECTDLGSTRUCT dialogOptions;
183+
private NETRESOURCEW netRes = new();
184+
private CONNECTDLGSTRUCTW dialogOptions;
184185

185-
/// <summary>
186-
/// Initializes a new instance of the <see cref="NetworkConnectionDialog"/> class.
187-
/// </summary>
186+
/// <summary>Initializes a new instance of the <see cref="NetworkConnectionDialog"/> class.</summary>
188187
public NetworkConnectionDialog()
189188
{
190-
dialogOptions.cbStructure = (uint)Marshal.SizeOf(typeof(Vanara.PInvoke.Mpr.CONNECTDLGSTRUCT));
191-
netRes.dwType = Vanara.PInvoke.Mpr.NETRESOURCEType.RESOURCETYPE_DISK;
189+
dialogOptions.cbStructure = (uint)Marshal.SizeOf(typeof(CONNECTDLGSTRUCTW));
190+
netRes.dwType = NET_RESOURCE_TYPE.RESOURCETYPE_DISK;
192191
}
193192

194193
/// <summary>Gets the connected device number. This value is only valid after successfully running the dialog.</summary>
195194
/// <value>The connected device number. The value is 1 for A:, 2 for B:, 3 for C:, and so on. If the user made a deviceless connection, the value is –1.</value>
196195
[Browsable(false)]
197-
public int ConnectedDeviceNumber
198-
=> dialogOptions.dwDevNum;
196+
public int ConnectedDeviceNumber => (int)dialogOptions.dwDevNum;
199197

200198
/// <summary>Gets or sets a value indicating whether to hide the check box allowing the user to restore the connection at logon.</summary>
201199
/// <value><c>true</c> if hiding restore connection check box; otherwise, <c>false</c>.</value>
202200
[DefaultValue(false), Category("Appearance"), Description("Hide the check box allowing the user to restore the connection at logon.")]
203201
public bool HideRestoreConnectionCheckBox
204202
{
205-
get => dialogOptions.dwFlags.IsFlagSet(Vanara.PInvoke.Mpr.CONN_DLG.CONNDLG_HIDE_BOX);
206-
set => dialogOptions.dwFlags = dialogOptions.dwFlags.SetFlags(Vanara.PInvoke.Mpr.CONN_DLG.CONNDLG_HIDE_BOX, value);
203+
get => dialogOptions.dwFlags.HasFlag(CONNECTDLGSTRUCT_FLAGS.CONNDLG_HIDE_BOX);
204+
set
205+
{
206+
if (value)
207+
dialogOptions.dwFlags |= CONNECTDLGSTRUCT_FLAGS.CONNDLG_HIDE_BOX;
208+
else
209+
dialogOptions.dwFlags &= ~CONNECTDLGSTRUCT_FLAGS.CONNDLG_HIDE_BOX;
210+
}
207211
}
208212

209213
/// <summary>Gets or sets a value indicating whether restore the connection at logon.</summary>
210214
/// <value><c>true</c> to restore connection at logon; otherwise, <c>false</c>.</value>
211215
[DefaultValue(false), Category("Behavior"), Description("Restore the connection at logon.")]
212216
public bool PersistConnectionAtLogon
213217
{
214-
get => dialogOptions.dwFlags.IsFlagSet(Vanara.PInvoke.Mpr.CONN_DLG.CONNDLG_PERSIST);
218+
get => dialogOptions.dwFlags.IsFlagSet(CONNECTDLGSTRUCT_FLAGS.CONNDLG_PERSIST);
215219
set
216220
{
217-
dialogOptions.dwFlags = dialogOptions.dwFlags.SetFlags(Vanara.PInvoke.Mpr.CONN_DLG.CONNDLG_PERSIST, value);
218-
dialogOptions.dwFlags = dialogOptions.dwFlags.SetFlags(Vanara.PInvoke.Mpr.CONN_DLG.CONNDLG_NOT_PERSIST, !value);
221+
dialogOptions.dwFlags = dialogOptions.dwFlags.SetFlags(CONNECTDLGSTRUCT_FLAGS.CONNDLG_PERSIST, value);
222+
dialogOptions.dwFlags = dialogOptions.dwFlags.SetFlags(CONNECTDLGSTRUCT_FLAGS.CONNDLG_NOT_PERSIST, !value);
219223
}
220224
}
221225

@@ -230,52 +234,64 @@ public bool PersistConnectionAtLogon
230234
/// <summary>Gets or sets the name of the remote network.</summary>
231235
/// <value>The name of the remote network.</value>
232236
[DefaultValue(null), Category("Behavior"), Description("The value displayed in the path field.")]
233-
public string RemoteNetworkName { get => netRes.lpRemoteName; set => netRes.lpRemoteName = value; }
237+
public string RemoteNetworkName
238+
{
239+
get => netRes.lpRemoteName.ToString();
240+
set
241+
{
242+
unsafe
243+
{
244+
fixed (char* lpcRemoteName = value)
245+
netRes.lpRemoteName = lpcRemoteName;
246+
}
247+
}
248+
}
234249

235250
/// <summary>Gets or sets a value indicating whether to enter the most recently used paths into the combination box.</summary>
236251
/// <value><c>true</c> to use MRU path; otherwise, <c>false</c>.</value>
237252
/// <exception cref="InvalidOperationException">UseMostRecentPath</exception>
238253
[DefaultValue(false), Category("Behavior"), Description("Enter the most recently used paths into the combination box.")]
239254
public bool UseMostRecentPath
240255
{
241-
get => dialogOptions.dwFlags.IsFlagSet(Vanara.PInvoke.Mpr.CONN_DLG.CONNDLG_USE_MRU);
256+
get => dialogOptions.dwFlags.IsFlagSet(CONNECTDLGSTRUCT_FLAGS.CONNDLG_USE_MRU);
242257
set
243258
{
244259
if (value && !string.IsNullOrEmpty(RemoteNetworkName))
245260
throw new InvalidOperationException($"{nameof(UseMostRecentPath)} cannot be set to true if {nameof(RemoteNetworkName)} has a value.");
246261

247-
dialogOptions.dwFlags = dialogOptions.dwFlags.SetFlags(Vanara.PInvoke.Mpr.CONN_DLG.CONNDLG_USE_MRU, value);
262+
dialogOptions.dwFlags = dialogOptions.dwFlags.SetFlags(CONNECTDLGSTRUCT_FLAGS.CONNDLG_USE_MRU, value);
248263
}
249264
}
250265

251266
/// <inheritdoc/>
252-
public override void Reset()
267+
public unsafe override void Reset()
253268
{
254-
dialogOptions.dwDevNum = -1;
269+
dialogOptions.dwDevNum = unchecked((uint)-1);
255270
dialogOptions.dwFlags = 0;
256-
dialogOptions.lpConnRes = IntPtr.Zero;
271+
dialogOptions.lpConnRes = null;
257272
ReadOnlyPath = false;
258273
}
259274

260275
/// <inheritdoc/>
261-
protected override bool RunDialog(IntPtr hwndOwner)
276+
protected unsafe override bool RunDialog(IntPtr hwndOwner)
262277
{
263-
using var lpNetResource = Vanara.InteropServices.SafeCoTaskMemHandle.CreateFromStructure(netRes);
278+
dialogOptions.hwndOwner = new(hwndOwner);
264279

265-
dialogOptions.hwndOwner = hwndOwner;
266-
dialogOptions.lpConnRes = lpNetResource.DangerousGetHandle();
280+
fixed (NETRESOURCEW* lpConnRes = &netRes)
281+
dialogOptions.lpConnRes = lpConnRes;
267282

268-
if (ReadOnlyPath && !string.IsNullOrEmpty(netRes.lpRemoteName))
269-
dialogOptions.dwFlags |= Vanara.PInvoke.Mpr.CONN_DLG.CONNDLG_RO_PATH;
283+
if (ReadOnlyPath && !string.IsNullOrEmpty(netRes.lpRemoteName.ToString()))
284+
dialogOptions.dwFlags |= CONNECTDLGSTRUCT_FLAGS.CONNDLG_RO_PATH;
270285

271-
var result = Vanara.PInvoke.Mpr.WNetConnectionDialog1(dialogOptions);
286+
var result = PInvoke.WNetConnectionDialog1W(ref dialogOptions);
272287

273-
dialogOptions.lpConnRes = IntPtr.Zero;
288+
dialogOptions.lpConnRes = null;
274289

275-
if (result == unchecked((uint)-1))
290+
if ((uint)result == unchecked((uint)-1))
276291
return false;
277292

278-
result.ThrowIfFailed();
293+
if (result == 0)
294+
throw new Win32Exception("Cannot display dialog");
279295

280296
return true;
281297
}

src/Files.App/Services/NetworkService.cs

Lines changed: 39 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33

44
using System.Runtime.InteropServices;
55
using System.Text;
6-
using Vanara.InteropServices;
76
using Vanara.PInvoke;
87
using Vanara.Windows.Shell;
9-
using static Vanara.PInvoke.AdvApi32;
10-
using static Vanara.PInvoke.Mpr;
8+
using Windows.Win32;
9+
using Windows.Win32.Foundation;
10+
using Windows.Win32.NetworkManagement.WNet;
11+
using Windows.Win32.Security.Credentials;
1112

1213
namespace Files.App.Services
1314
{
@@ -180,7 +181,12 @@ public async Task UpdateShortcutsAsync()
180181
/// <inheritdoc/>
181182
public bool DisconnectNetworkDrive(ILocatableFolder drive)
182183
{
183-
return WNetCancelConnection2(drive.Path.TrimEnd('\\'), CONNECT.CONNECT_UPDATE_PROFILE, true).Succeeded;
184+
return
185+
PInvoke.WNetCancelConnection2W(
186+
drive.Path.TrimEnd('\\'),
187+
(uint)NET_USE_CONNECT_FLAGS.CONNECT_UPDATE_PROFILE,
188+
true)
189+
is WIN32_ERROR.NO_ERROR;
184190
}
185191

186192
/// <inheritdoc/>
@@ -198,39 +204,51 @@ public Task OpenMapNetworkDriveDialogAsync()
198204
/// <inheritdoc/>
199205
public async Task<bool> AuthenticateNetworkShare(string path)
200206
{
201-
var netRes = new NETRESOURCE()
207+
var netRes = new NETRESOURCEW() { dwType = NET_RESOURCE_TYPE.RESOURCETYPE_DISK };
208+
209+
unsafe
202210
{
203-
dwType = NETRESOURCEType.RESOURCETYPE_DISK,
204-
lpRemoteName = path
205-
};
211+
fixed (char* lpcPath = path)
212+
netRes.lpRemoteName = new PWSTR(lpcPath);
213+
}
206214

207215
// If credentials are saved, this will return NO_ERROR
208-
Win32Error connectionError = WNetAddConnection3(HWND.NULL, netRes, null, null, 0);
216+
var res = (WIN32_ERROR)PInvoke.WNetAddConnection3W(new(nint.Zero), netRes, null, null, 0);
209217

210-
if (connectionError == Win32Error.ERROR_LOGON_FAILURE || connectionError == Win32Error.ERROR_ACCESS_DENIED)
218+
if (res == WIN32_ERROR.ERROR_LOGON_FAILURE || res == WIN32_ERROR.ERROR_ACCESS_DENIED)
211219
{
212220
var dialog = DynamicDialogFactory.GetFor_CredentialEntryDialog(path);
213221
await dialog.ShowAsync();
214222
var credentialsReturned = dialog.ViewModel.AdditionalData as string[];
215223

216224
if (credentialsReturned is not null && credentialsReturned[1] != null)
217225
{
218-
connectionError = WNetAddConnection3(HWND.NULL, netRes, credentialsReturned[1], credentialsReturned[0], 0);
219-
if (credentialsReturned[2] == "y" && connectionError == Win32Error.NO_ERROR)
226+
res = (WIN32_ERROR)PInvoke.WNetAddConnection3W(new(nint.Zero), netRes, credentialsReturned[1], credentialsReturned[0], 0);
227+
if (credentialsReturned[2] == "y" && res == WIN32_ERROR.NO_ERROR)
220228
{
221-
var creds = new CREDENTIAL
229+
var creds = new CREDENTIALW()
222230
{
223-
TargetName = new StrPtrAuto(path.Substring(2)),
224-
UserName = new StrPtrAuto(credentialsReturned[0]),
225231
Type = CRED_TYPE.CRED_TYPE_DOMAIN_PASSWORD,
226232
AttributeCount = 0,
227233
Persist = CRED_PERSIST.CRED_PERSIST_ENTERPRISE
228234
};
229235

230-
byte[] bPassword = Encoding.Unicode.GetBytes(credentialsReturned[1]);
231-
creds.CredentialBlobSize = (uint)bPassword.Length;
232-
creds.CredentialBlob = Marshal.StringToCoTaskMemUni(credentialsReturned[1]);
233-
CredWrite(creds, 0);
236+
unsafe
237+
{
238+
fixed (char* lpcTargetName = path.Substring(2))
239+
creds.TargetName = new(lpcTargetName);
240+
241+
fixed (char* lpcUserName = credentialsReturned[0])
242+
creds.UserName = new(lpcUserName);
243+
244+
byte[] bPassword = Encoding.Unicode.GetBytes(credentialsReturned[1]);
245+
fixed (byte* lpCredentialBlob = bPassword)
246+
creds.CredentialBlob = lpCredentialBlob;
247+
248+
creds.CredentialBlobSize = (uint)bPassword.Length;
249+
}
250+
251+
PInvoke.CredWrite(creds, 0);
234252
}
235253
}
236254
else
@@ -239,13 +257,13 @@ public async Task<bool> AuthenticateNetworkShare(string path)
239257
}
240258
}
241259

242-
if (connectionError == Win32Error.NO_ERROR)
260+
if (res == WIN32_ERROR.NO_ERROR)
243261
{
244262
return true;
245263
}
246264
else
247265
{
248-
await DialogDisplayHelper.ShowDialogAsync("NetworkFolderErrorDialogTitle".GetLocalizedResource(), connectionError.ToString().Split(":")[1].Trim());
266+
await DialogDisplayHelper.ShowDialogAsync("NetworkFolderErrorDialogTitle".GetLocalizedResource(), res.ToString());
249267

250268
return false;
251269
}

src/Files.App/ViewModels/UserControls/Previews/ShellPreviewViewModel.cs

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
using Windows.Win32.Graphics.Dxgi;
1212
using Windows.Win32.Graphics.DirectComposition;
1313
using WinRT;
14+
using Windows.Win32;
15+
using Windows.Win32.Graphics.Dwm;
1416
using static Vanara.PInvoke.ShlwApi;
1517
using static Vanara.PInvoke.User32;
1618

@@ -178,7 +180,18 @@ private unsafe bool ChildWindowToXaml(IntPtr parent, UIElement presenter)
178180
Marshal.ReleaseComObject(d3d11Device);
179181
Marshal.ReleaseComObject(d3d11DeviceContext);
180182

181-
return DwmApi.DwmSetWindowAttribute(hwnd, DwmApi.DWMWINDOWATTRIBUTE.DWMWA_CLOAK, true).Succeeded;
183+
unsafe
184+
{
185+
var dwAttrib = Convert.ToUInt32(true);
186+
187+
return
188+
PInvoke.DwmSetWindowAttribute(
189+
new((nint)hwnd),
190+
DWMWINDOWATTRIBUTE.DWMWA_CLOAK,
191+
&dwAttrib,
192+
(uint)Marshal.SizeOf(dwAttrib))
193+
.Succeeded;
194+
}
182195
}
183196

184197
public void UnloadPreview()
@@ -195,15 +208,35 @@ public void PointerEntered(bool onPreview)
195208
{
196209
if (onPreview)
197210
{
198-
DwmApi.DwmSetWindowAttribute(hwnd, DwmApi.DWMWINDOWATTRIBUTE.DWMWA_CLOAK, false);
211+
unsafe
212+
{
213+
var dwAttrib = Convert.ToUInt32(false);
214+
215+
PInvoke.DwmSetWindowAttribute(
216+
new((nint)hwnd),
217+
DWMWINDOWATTRIBUTE.DWMWA_CLOAK,
218+
&dwAttrib,
219+
(uint)Marshal.SizeOf(dwAttrib));
220+
}
221+
199222
if (isOfficePreview)
200223
Win32Helper.SetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE, 0);
201224
}
202225
else
203226
{
204227
Win32Helper.SetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE,
205228
(nint)(WindowStylesEx.WS_EX_LAYERED | WindowStylesEx.WS_EX_COMPOSITED));
206-
DwmApi.DwmSetWindowAttribute(hwnd, DwmApi.DWMWINDOWATTRIBUTE.DWMWA_CLOAK, true);
229+
230+
unsafe
231+
{
232+
var dwAttrib = Convert.ToUInt32(true);
233+
234+
PInvoke.DwmSetWindowAttribute(
235+
new((nint)hwnd),
236+
DWMWINDOWATTRIBUTE.DWMWA_CLOAK,
237+
&dwAttrib,
238+
(uint)Marshal.SizeOf(dwAttrib));
239+
}
207240
}
208241
}
209242
}

0 commit comments

Comments
 (0)