Skip to content

Commit 27d9db1

Browse files
Code Quality: Properly handle cancellation and null shell items in WindowsDialogService (#17310)
1 parent d3c6d87 commit 27d9db1

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

src/Files.App/Services/Windows/WindowsDialogService.cs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,17 @@ public unsafe bool Open_FileOpenDialog(nint hWnd, bool pickFoldersOnly, string[]
6565
pDialog.Get()->SetDefaultFolder(pDefaultFolderShellItem.Get());
6666

6767
// Show the dialog
68-
pDialog.Get()->Show(new HWND(hWnd));
68+
hr = pDialog.Get()->Show(new HWND(hWnd));
69+
if (hr.Value == unchecked((int)0x800704C7)) // HRESULT_FROM_WIN32(ERROR_CANCELLED)
70+
return false;
71+
72+
hr.ThrowOnFailure();
6973

7074
// Get the file that user chose
7175
using ComPtr<IShellItem> pResultShellItem = default;
7276
pDialog.Get()->GetResult(pResultShellItem.GetAddressOf());
73-
if (pResultShellItem.Get() == null)
74-
throw new COMException("FileSaveDialog returned invalid shell item.");
77+
if (pResultShellItem.Get() is null)
78+
throw new COMException("FileOpenDialog returned invalid shell item.");
7579
pResultShellItem.Get()->GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out var lpFilePath);
7680
filePath = lpFilePath.ToString();
7781

@@ -135,12 +139,16 @@ public unsafe bool Open_FileSaveDialog(nint hWnd, bool pickFoldersOnly, string[]
135139
pDialog.Get()->SetDefaultFolder(pDefaultFolderShellItem.Get());
136140

137141
// Show the dialog
138-
pDialog.Get()->Show(new HWND(hWnd));
142+
hr = pDialog.Get()->Show(new HWND(hWnd));
143+
if (hr.Value == unchecked((int)0x800704C7)) // HRESULT_FROM_WIN32(ERROR_CANCELLED)
144+
return false;
145+
146+
hr.ThrowOnFailure();
139147

140148
// Get the file that user chose
141149
using ComPtr<IShellItem> pResultShellItem = default;
142150
pDialog.Get()->GetResult(pResultShellItem.GetAddressOf());
143-
if (pResultShellItem.Get() == null)
151+
if (pResultShellItem.Get() is null)
144152
throw new COMException("FileSaveDialog returned invalid shell item.");
145153
pResultShellItem.Get()->GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out var lpFilePath);
146154
filePath = lpFilePath.ToString();

0 commit comments

Comments
 (0)