[ZoomIt] Fix screenshot save accuracy issue and GDI object leak (#43375)

<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request
This fixes two issues with the ZoomIt screenshot save function:

- The "actual size" saved bitmap was recomputed from the zoomed-in
viewport, leading to artefacts and a non-1:1 pixel accurate output if
smooth mode was active.
- Two bitmap objects were not deleted after being selected, leading to a
leak of 1 or 2 GDI objects per screenshot save operation.

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist

- [x] Closes: #43323
- [x] Closes: #43352
- [ ] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [ ] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end-user-facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments
### GDI object leak
In the prior code, bitmap objects were created:

```cpp
            // Capture the screen before displaying the save dialog
            hInterimSaveDc = CreateCompatibleDC( hdcScreen );
            hInterimSaveBitmap = CreateCompatibleBitmap( hdcScreen, copyWidth, copyHeight );
            SelectObject( hInterimSaveDc, hInterimSaveBitmap );
...
                    hSaveBitmap = CreateCompatibleBitmap( hdcScreen, saveWidth, saveHeight );
                    SelectObject( hSaveDc, hSaveBitmap );
```

but were not deleted in the clean-up:

```cpp
            DeleteDC( hInterimSaveDc );
            DeleteDC( hSaveDc );
```

Deleting their associated device contexts orphans the bitmaps and the
GDI objects will not be recovered until ZoomIt is closed.

### Fix
The code now uses RAII for handles to DCs and Bitmaps, e.g.:

```cpp
                    wil::unique_hdc hdcZoomed( CreateCompatibleDC(hdcScreen) );
                    wil::unique_hbitmap hbmZoomed(
                        CreateCompatibleBitmap( hdcScreen, copyWidth, copyHeight ) );
                    SelectObject( hdcZoomed.get(), hbmZoomed.get() );
```

The handles are automatically cleaned up when the variables go out of
scope.

The existing `DeleteDC` code has been removed.

### Screenshot Actual Size save issue

ZoomIt's save screenshot routine operated on the currently-displayed
view, i.e. the zoomed-in viewport, executing a copy of the full monitor
resolution image to begin:

```cpp
            StretchBlt( hInterimSaveDc,
                        0, 0,
                        copyWidth, copyHeight,
                        hdcScreen,
                        monInfo.rcMonitor.left + copyX,
                        monInfo.rcMonitor.top + copyY,
                        copyWidth, copyHeight,
                        SRCCOPY|CAPTUREBLT );
```
(Here hdcScreen represents the zoomed-in image.)

When "Actual size" was selected by the user, this bitmap was scaled back
down to attempt to reproduce the 1:1 pixel source:

```cpp
                    StretchBlt( hSaveDc,
                                0, 0,
                                saveWidth, saveHeight,
                                hInterimSaveDc,
                                0,
                                0,
                                copyWidth, copyHeight,
                                SRCCOPY | CAPTUREBLT );
				
                    SavePng( targetFilePath, hSaveBitmap );
```

This mostly works if the smooth mode is not applied because the zoom
levels tend to produce integer zoomed pixel sizes, although it still
produces inexact results at times.

The main issue is that the new smooth mode produces a halftone-smoothed
output on the display. Attempting to scale this back down to a
pixel-accurate source removes high frequency detail and does not reflect
the underlying bitmap:

Original source:
<img width="523" height="186" alt="image"
src="https://github.com/user-attachments/assets/7a6dca02-8608-44ed-917f-c6fd1a7b112c"
/>

"Actual size" save result before fix:
<img width="524" height="211" alt="image"
src="https://github.com/user-attachments/assets/29c63018-1e8d-4e74-a572-3615686aaa61"
/>

### Fix

This fix reverses the prior logic. Instead of using the zoomed-in
viewport as the screenshot source, we start by blitting a copy of the
source bitmap itself, from `hdcScreenCompat`. If a zoomed screenshot is
required, this is used as the source of the resize, i.e. we replicate
the zoom the user sees in their viewport.

This approach:

- Is faster and saves memory. It removes the need for an initial
`StretchBlt` operation, and the working bitmap itself is significantly
smaller if the user is zoomed in.
- Saves on the second resize operation if "Actual size" is chosen. We
can simply save the copy as-is.
- Removes the need to care about monitor coords. All calculations are
relative to the top-left of the source bitmap copy.
- Simplifies the code. In addition to being able to remove some code,
locality is improved - the creation of the zoomed image (and the
application of smoothing, if required) is now immediately next to where
it is saved.

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

(Manual validation on standalone ZoomIt build.)

- Confirmed that "Actual size" screenshots are now 1:1 copies of the
underlying bitmap, not scaled copies of the screen display.
- Confirmed that screenshots no longer leak GDI objects in either
"Zoomed" or "Actual size" modes.
- Tested cropped and non-cropped saves, i.e. using
<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>S</kbd> versus
<kbd>Ctrl</kbd>+<kbd>S</kbd>.
- Tested that user-added drawing/text was preserved in screenshots.
- Tested that both smooth and non-smooth zoom modes operate as they did
previously.
- Tested on multiple monitors, including a high-DPI external monitor
running at 175% scaling.

---------

Co-authored-by: Leilei Zhang <leilzh@microsoft.com>
This commit is contained in:
Dave Rayment
2025-11-13 04:51:54 +00:00
committed by GitHub
parent 8fc43e1a22
commit 9f95d9b477
2 changed files with 59 additions and 58 deletions

View File

@@ -141,7 +141,7 @@ bla
BLACKFRAME
BLENDFUNCTION
Blockquotes
Blt
blt
BLURBEHIND
BLURREGION
bmi
@@ -1873,6 +1873,7 @@ UPDATENOW
UPDATEREGISTRY
updown
UPGRADINGPRODUCTCODE
upscaling
Uptool
urld
Usb

View File

@@ -6440,12 +6440,10 @@ LRESULT APIENTRY MainWndProc(
GetCursorPos(&local_savedCursorPos);
}
HBITMAP hInterimSaveBitmap;
HDC hInterimSaveDc;
HBITMAP hSaveBitmap;
HDC hSaveDc;
int copyX, copyY;
int copyWidth, copyHeight;
// Determine the user's desired save area in zoomed viewport coordinates.
// This will be the entire viewport if the user does not select a crop
// rectangle.
int copyX = 0, copyY = 0, copyWidth = width, copyHeight = height;
if ( LOWORD( wParam ) == IDC_SAVE_CROP )
{
@@ -6460,55 +6458,51 @@ LRESULT APIENTRY MainWndProc(
}
break;
}
auto copyRc = selectRectangle.SelectedRect();
selectRectangle.Stop();
g_RecordCropping = FALSE;
copyX = copyRc.left;
copyY = copyRc.top;
copyWidth = copyRc.right - copyRc.left;
copyHeight = copyRc.bottom - copyRc.top;
}
else
{
copyX = 0;
copyY = 0;
copyWidth = width;
copyHeight = height;
}
OutputDebug( L"***x: %d, y: %d, width: %d, height: %d\n", copyX, copyY, copyWidth, copyHeight );
RECT oldClipRect{};
GetClipCursor( &oldClipRect );
ClipCursor( NULL );
// Capture the screen before displaying the save dialog
hInterimSaveDc = CreateCompatibleDC( hdcScreen );
hInterimSaveBitmap = CreateCompatibleBitmap( hdcScreen, copyWidth, copyHeight );
SelectObject( hInterimSaveDc, hInterimSaveBitmap );
// Translate the viewport selection into coordinates for the 1:1 source
// bitmap hdcScreenCompat.
int viewportX, viewportY;
GetZoomedTopLeftCoordinates(
zoomLevel, &cursorPos, &viewportX, width, &viewportY, height );
hSaveDc = CreateCompatibleDC( hdcScreen );
#if SCALE_HALFTONE
SetStretchBltMode( hInterimSaveDc, HALFTONE );
SetStretchBltMode( hSaveDc, HALFTONE );
#else
// Use HALFTONE for better quality when smooth image is enabled
if (g_SmoothImage) {
SetStretchBltMode( hInterimSaveDc, HALFTONE );
SetStretchBltMode( hSaveDc, HALFTONE );
} else {
SetStretchBltMode( hInterimSaveDc, COLORONCOLOR );
SetStretchBltMode( hSaveDc, COLORONCOLOR );
}
#endif
StretchBlt( hInterimSaveDc,
0, 0,
copyWidth, copyHeight,
hdcScreen,
monInfo.rcMonitor.left + copyX,
monInfo.rcMonitor.top + copyY,
copyWidth, copyHeight,
SRCCOPY|CAPTUREBLT );
int saveX = viewportX + static_cast<int>( copyX / zoomLevel );
int saveY = viewportY + static_cast<int>( copyY / zoomLevel );
int saveWidth = static_cast<int>( copyWidth / zoomLevel );
int saveHeight = static_cast<int>( copyHeight / zoomLevel );
// Create a pixel-accurate copy of the desired area from the source bitmap.
wil::unique_hdc hdcActualSize( CreateCompatibleDC( hdcScreen ) );
wil::unique_hbitmap hbmActualSize(
CreateCompatibleBitmap( hdcScreen, saveWidth, saveHeight ) );
// Note: we do not need to restore the existing context later. The objects
// are transient and not reused.
SelectObject( hdcActualSize.get(), hbmActualSize.get() );
// Perform a direct 1:1 copy from the backing bitmap.
BitBlt( hdcActualSize.get(),
0, 0,
saveWidth, saveHeight,
hdcScreenCompat,
saveX, saveY,
SRCCOPY | CAPTUREBLT );
// Open the Save As dialog and capture the desired file path and whether to
// save the zoomed display or the source bitmap pixels.
g_bSaveInProgress = true;
memset( &openFileName, 0, sizeof(openFileName ));
openFileName.lStructSize = OPENFILENAME_SIZE_VERSION_400;
@@ -6524,6 +6518,7 @@ LRESULT APIENTRY MainWndProc(
"Actual size PNG\0*.png\0\0";
//"Actual size BMP\0*.bmp\0\0";
openFileName.lpstrFile = filePath;
if( GetSaveFileName( &openFileName ) )
{
TCHAR targetFilePath[MAX_PATH];
@@ -6533,42 +6528,47 @@ LRESULT APIENTRY MainWndProc(
_tcscat( targetFilePath, L".png" );
}
// Save image at screen size
if( openFileName.nFilterIndex == 1 )
if( openFileName.nFilterIndex == 2 )
{
SavePng( targetFilePath, hInterimSaveBitmap );
// Save at actual size.
SavePng( targetFilePath, hbmActualSize.get() );
}
// Save image scaled down to actual size
else
{
int saveWidth = static_cast<int>( copyWidth / zoomLevel );
int saveHeight = static_cast<int>( copyHeight / zoomLevel );
// Save zoomed-in image at screen resolution.
#if SCALE_HALFTONE
const int bltMode = HALFTONE;
#else
// Use HALFTONE for better quality when smooth image is enabled
const int bltMode = g_SmoothImage ? HALFTONE : COLORONCOLOR;
#endif
// Recreate the zoomed-in view by upscaling from our source bitmap.
wil::unique_hdc hdcZoomed( CreateCompatibleDC(hdcScreen) );
wil::unique_hbitmap hbmZoomed(
CreateCompatibleBitmap( hdcScreen, copyWidth, copyHeight ) );
SelectObject( hdcZoomed.get(), hbmZoomed.get() );
hSaveBitmap = CreateCompatibleBitmap( hdcScreen, saveWidth, saveHeight );
SelectObject( hSaveDc, hSaveBitmap );
SetStretchBltMode( hdcZoomed.get(), bltMode );
StretchBlt( hSaveDc,
StretchBlt( hdcZoomed.get(),
0, 0,
copyWidth, copyHeight,
hdcActualSize.get(),
0, 0,
saveWidth, saveHeight,
hInterimSaveDc,
0,
0,
copyWidth, copyHeight,
SRCCOPY | CAPTUREBLT );
SavePng( targetFilePath, hSaveBitmap );
SavePng( targetFilePath, hbmZoomed.get() );
}
}
g_bSaveInProgress = false;
DeleteDC( hInterimSaveDc );
DeleteDC( hSaveDc );
if( lParam != SHALLOW_ZOOM )
{
SetCursorPos(local_savedCursorPos.x, local_savedCursorPos.y);
SetCursorPos( local_savedCursorPos.x, local_savedCursorPos.y );
}
ClipCursor( &oldClipRect );
break;
}