[New Utility]Crop And Lock (#27832)

* [CropAndLock]Original POC code dump

* Project rename and delete solution

* Remove unused architectures

* Update cppwinrt to be in line with the solution

* Add to PowerToys solution and fix build errors

* Initial module interface empty project

* Module skeleton based on AlwaysOnTop

* Add loggers to module interface

* Add crop and lock to the runner

* Enable starts and disable kills the process

* Events reacting to hotkeys

* Main application reacting to events

* Initialize unhandled exception handling

* Singleton in line with other projects

* Also exit when PowerToys exit is detected

* Create Settings page

* React to shortcut changes in Settings

* Disable Crop and Lock through an Event

* Disable running Crop and Lock standalone

* Remove Crop and Lock tray icon

* Module Interface dll version

* Fix main app resource file to include version

* Make pch conditional on CI build

* Add to signing

* Remove settings screen opened by removed tray icon

* Fix spellcheck

* Yet another fix for spellcheck

* Fix disabling utility

* Fix solution build configurations

* Fix C++ analyzer errors

* Try to fix pre-compiled header CI errors

* Fix crash while exiting with an active reparent window

* Fix missing reference when building in release CI

* Add OOBE page

* GPO: Add admx and adml file changes

* GPO: react to changes in GPO

* Add quick access flyout menu entry

* Use Crop And Lock icon

* Use actual images for Settings and OOBE

* Module and app telemetry

* Add entry to README.md

* Add to process lists

* Additional logging

* Attribution in Settings page

* Add attribution to Community.md

* Fix spellcheck

* Fix typo in strings

* Fix crash when window handle is no longer valid

* Update COMMUNITY.md

* Fix supportedOS in manifest

* Don't show msgbox if detecting second instance

* Remove unused hotkey

* Tweak attribution

* Fix attribution spellcheck
This commit is contained in:
Jaime Bernardo 2023-08-10 10:46:33 +01:00 committed by GitHub
parent d2c5b365fa
commit 7ecfc58caa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
73 changed files with 3006 additions and 13 deletions

View File

@ -15,6 +15,7 @@ edwinzap
Essey Essey
Garside Garside
Gershaft Gershaft
Guo
hallatore hallatore
Harmath Harmath
Hemmerlein Hemmerlein
@ -23,9 +24,11 @@ Jaswal
jefflord jefflord
Kamra Kamra
Karthick Karthick
kevinguo
Krigun Krigun
Luecking Luecking
Mahalingam Mahalingam
Mikhayelyan
mshtang mshtang
Myrvold Myrvold
naveensrinivasan naveensrinivasan
@ -33,6 +36,7 @@ nVidia
Ponten Ponten
Pooja Pooja
robmen robmen
robmikh
Schoen Schoen
skycommand skycommand
snickler snickler

View File

@ -674,6 +674,7 @@ hcblack
HCERTSTORE HCERTSTORE
HCRYPTHASH HCRYPTHASH
HCRYPTPROV HCRYPTPROV
hcursor
hcwhite hcwhite
hdc hdc
hdrop hdrop
@ -742,7 +743,7 @@ hstring
hsv hsv
htcfreek htcfreek
HTCLIENT HTCLIENT
HTHUMBNAIL hthumbnail
HTOUCHINPUT HTOUCHINPUT
HTTRANSPARENT HTTRANSPARENT
HVal HVal
@ -1529,6 +1530,7 @@ RECTDESTINATION
RECTL RECTL
rectp rectp
rects rects
RECTSOURCE
redirectedfrom redirectedfrom
Redist Redist
redistributable redistributable
@ -1566,6 +1568,9 @@ Removelnk
renamable renamable
RENAMEONCOLLISION RENAMEONCOLLISION
Renamer Renamer
reparent
reparented
reparenting
reparse reparse
reportbug reportbug
requery requery

View File

@ -121,6 +121,7 @@ TestCase\("[^"]+"
\\restart \\restart
\\restore \\restore
\\result \\result
\\robmikh
\\rotating \\rotating
\\runner \\runner
\\runtimes \\runtimes

View File

@ -33,6 +33,9 @@
"PowerToys.ColorPickerUI.dll", "PowerToys.ColorPickerUI.dll",
"PowerToys.ColorPickerUI.exe", "PowerToys.ColorPickerUI.exe",
"PowerToys.CropAndLockModuleInterface.dll",
"PowerToys.CropAndLock.exe",
"PowerToys.PowerOCRModuleInterface.dll", "PowerToys.PowerOCRModuleInterface.dll",
"PowerToys.PowerOCR.dll", "PowerToys.PowerOCR.dll",
"PowerToys.PowerOCR.exe", "PowerToys.PowerOCR.exe",

View File

@ -107,6 +107,10 @@ Randy contributed Registry Preview and some very early conversations about keybo
Find My Mouse is based on Raymond Chen's SuperSonar. Find My Mouse is based on Raymond Chen's SuperSonar.
### [@robmikh](https://github.com/robmikh) - Robert Mikhayelyan
Crop And Lock is based on the original work of Robert Mikhayelyan, with Program Manager support from [@kevinguo305](https://github.com/kevinguo305) - Kevin Guo.
### Microsoft InVEST team ### Microsoft InVEST team
This amazing team helped PowerToys develop PowerToys Run and Keyboard manager as well as update our Settings to v2. @alekhyareddy28, @arjunbalgovind, @jyuwono @laviusmotileng-ms, @ryanbodrug-microsoft, @saahmedm, @somil55, @traies, @udit3333 This amazing team helped PowerToys develop PowerToys Run and Keyboard manager as well as update our Settings to v2. @alekhyareddy28, @arjunbalgovind, @jyuwono @laviusmotileng-ms, @ryanbodrug-microsoft, @saahmedm, @somil55, @traies, @udit3333

View File

@ -530,6 +530,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Community.PowerToys.Run.Plu
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Community.PowerToys.Run.Plugin.ValueGenerator.UnitTests", "src\modules\launcher\Plugins\Community.PowerToys.Run.Plugin.ValueGenerator.UnitTests\Community.PowerToys.Run.Plugin.ValueGenerator.UnitTests.csproj", "{90F9FA90-2C20-4004-96E6-F3B78151F5A5}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Community.PowerToys.Run.Plugin.ValueGenerator.UnitTests", "src\modules\launcher\Plugins\Community.PowerToys.Run.Plugin.ValueGenerator.UnitTests\Community.PowerToys.Run.Plugin.ValueGenerator.UnitTests.csproj", "{90F9FA90-2C20-4004-96E6-F3B78151F5A5}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CropAndLock", "CropAndLock", "{3B227528-4BA6-4CAF-B44A-A10C78A64849}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CropAndLock", "src\modules\CropAndLock\CropAndLock\CropAndLock.vcxproj", "{F5E1146E-B7B3-4E11-85FD-270A500BD78C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CropAndLockModuleInterface", "src\modules\CropAndLock\CropAndLockModuleInterface\CropAndLockModuleInterface.vcxproj", "{3157FA75-86CF-4EE2-8F62-C43F776493C6}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM64 = Debug|ARM64 Debug|ARM64 = Debug|ARM64
@ -2276,6 +2282,30 @@ Global
{90F9FA90-2C20-4004-96E6-F3B78151F5A5}.Release|x64.Build.0 = Release|x64 {90F9FA90-2C20-4004-96E6-F3B78151F5A5}.Release|x64.Build.0 = Release|x64
{90F9FA90-2C20-4004-96E6-F3B78151F5A5}.Release|x86.ActiveCfg = Release|x64 {90F9FA90-2C20-4004-96E6-F3B78151F5A5}.Release|x86.ActiveCfg = Release|x64
{90F9FA90-2C20-4004-96E6-F3B78151F5A5}.Release|x86.Build.0 = Release|x64 {90F9FA90-2C20-4004-96E6-F3B78151F5A5}.Release|x86.Build.0 = Release|x64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Debug|ARM64.ActiveCfg = Debug|ARM64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Debug|ARM64.Build.0 = Debug|ARM64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Debug|x64.ActiveCfg = Debug|x64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Debug|x64.Build.0 = Debug|x64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Debug|x86.ActiveCfg = Debug|x64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Debug|x86.Build.0 = Debug|x64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Release|ARM64.ActiveCfg = Release|ARM64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Release|ARM64.Build.0 = Release|ARM64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Release|x64.ActiveCfg = Release|x64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Release|x64.Build.0 = Release|x64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Release|x86.ActiveCfg = Release|x64
{F5E1146E-B7B3-4E11-85FD-270A500BD78C}.Release|x86.Build.0 = Release|x64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Debug|ARM64.ActiveCfg = Debug|ARM64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Debug|ARM64.Build.0 = Debug|ARM64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Debug|x64.ActiveCfg = Debug|x64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Debug|x64.Build.0 = Debug|x64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Debug|x86.ActiveCfg = Debug|x64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Debug|x86.Build.0 = Debug|x64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Release|ARM64.ActiveCfg = Release|ARM64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Release|ARM64.Build.0 = Release|ARM64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Release|x64.ActiveCfg = Release|x64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Release|x64.Build.0 = Release|x64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Release|x86.ActiveCfg = Release|x64
{3157FA75-86CF-4EE2-8F62-C43F776493C6}.Release|x86.Build.0 = Release|x64
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@ -2467,6 +2497,9 @@ Global
{500DED3E-CFB5-4ED5-ACC6-02B3D6DC336D} = {4AFC9975-2456-4C70-94A4-84073C1CED93} {500DED3E-CFB5-4ED5-ACC6-02B3D6DC336D} = {4AFC9975-2456-4C70-94A4-84073C1CED93}
{D095BE44-1F2E-463E-A494-121892A75EA2} = {4AFC9975-2456-4C70-94A4-84073C1CED93} {D095BE44-1F2E-463E-A494-121892A75EA2} = {4AFC9975-2456-4C70-94A4-84073C1CED93}
{90F9FA90-2C20-4004-96E6-F3B78151F5A5} = {4AFC9975-2456-4C70-94A4-84073C1CED93} {90F9FA90-2C20-4004-96E6-F3B78151F5A5} = {4AFC9975-2456-4C70-94A4-84073C1CED93}
{3B227528-4BA6-4CAF-B44A-A10C78A64849} = {4574FDD0-F61D-4376-98BF-E5A1262C11EC}
{F5E1146E-B7B3-4E11-85FD-270A500BD78C} = {3B227528-4BA6-4CAF-B44A-A10C78A64849}
{3157FA75-86CF-4EE2-8F62-C43F776493C6} = {3B227528-4BA6-4CAF-B44A-A10C78A64849}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C3A2F9D1-7930-4EF4-A6FC-7EE0A99821D0} SolutionGuid = {C3A2F9D1-7930-4EF4-A6FC-7EE0A99821D0}

View File

@ -18,12 +18,13 @@ Microsoft PowerToys is a set of utilities for power users to tune and streamline
| | Current utilities: | | | | Current utilities: | |
|--------------|--------------------|--------------| |--------------|--------------------|--------------|
| [Always on Top](https://aka.ms/PowerToysOverview_AoT) | [PowerToys Awake](https://aka.ms/PowerToysOverview_Awake) | [Color Picker](https://aka.ms/PowerToysOverview_ColorPicker) | | [Always on Top](https://aka.ms/PowerToysOverview_AoT) | [PowerToys Awake](https://aka.ms/PowerToysOverview_Awake) | [Color Picker](https://aka.ms/PowerToysOverview_ColorPicker) |
| [FancyZones](https://aka.ms/PowerToysOverview_FancyZones) | [File Explorer Add-ons](https://aka.ms/PowerToysOverview_FileExplorerAddOns) | [File Locksmith](https://aka.ms/PowerToysOverview_FileLocksmith) | | [Crop And Lock](https://aka.ms/PowerToysOverview_CropAndLock) | [FancyZones](https://aka.ms/PowerToysOverview_FancyZones) | [File Explorer Add-ons](https://aka.ms/PowerToysOverview_FileExplorerAddOns) |
| [Hosts File Editor](https://aka.ms/PowerToysOverview_HostsFileEditor) | [Image Resizer](https://aka.ms/PowerToysOverview_ImageResizer) | [Keyboard Manager](https://aka.ms/PowerToysOverview_KeyboardManager) | | [File Locksmith](https://aka.ms/PowerToysOverview_FileLocksmith) | [Hosts File Editor](https://aka.ms/PowerToysOverview_HostsFileEditor) | [Image Resizer](https://aka.ms/PowerToysOverview_ImageResizer) |
| [Mouse utilities](https://aka.ms/PowerToysOverview_MouseUtilities) | [Mouse Without Borders](https://aka.ms/PowerToysOverview_MouseWithoutBorders) | [Peek](https://aka.ms/PowerToysOverview_Peek) | | [Keyboard Manager](https://aka.ms/PowerToysOverview_KeyboardManager) | [Mouse utilities](https://aka.ms/PowerToysOverview_MouseUtilities) | [Mouse Without Borders](https://aka.ms/PowerToysOverview_MouseWithoutBorders) |
| [Paste as Plain Text](https://aka.ms/PowerToysOverview_PastePlain) | [PowerRename](https://aka.ms/PowerToysOverview_PowerRename) | [PowerToys Run](https://aka.ms/PowerToysOverview_PowerToysRun) | | [Peek](https://aka.ms/PowerToysOverview_Peek) | [Paste as Plain Text](https://aka.ms/PowerToysOverview_PastePlain) | [PowerRename](https://aka.ms/PowerToysOverview_PowerRename) |
| [Quick Accent](https://aka.ms/PowerToysOverview_QuickAccent) | [Registry Preview](https://aka.ms/PowerToysOverview_RegistryPreview) | [Screen Ruler](https://aka.ms/PowerToysOverview_ScreenRuler) | | [PowerToys Run](https://aka.ms/PowerToysOverview_PowerToysRun) | [Quick Accent](https://aka.ms/PowerToysOverview_QuickAccent) | [Registry Preview](https://aka.ms/PowerToysOverview_RegistryPreview) |
| [Shortcut Guide](https://aka.ms/PowerToysOverview_ShortcutGuide) | [Text Extractor](https://aka.ms/PowerToysOverview_TextExtractor) | [Video Conference Mute](https://aka.ms/PowerToysOverview_VideoConference) | | [Screen Ruler](https://aka.ms/PowerToysOverview_ScreenRuler) | [Shortcut Guide](https://aka.ms/PowerToysOverview_ShortcutGuide) | [Text Extractor](https://aka.ms/PowerToysOverview_TextExtractor) |
| [Video Conference Mute](https://aka.ms/PowerToysOverview_VideoConference) |
## Installing and running Microsoft PowerToys ## Installing and running Microsoft PowerToys

View File

@ -1005,7 +1005,7 @@ UINT __stdcall TerminateProcessesCA(MSIHANDLE hInstall)
} }
processes.resize(bytes / sizeof(processes[0])); processes.resize(bytes / sizeof(processes[0]));
std::array<std::wstring_view, 27> processesToTerminate = { std::array<std::wstring_view, 28> processesToTerminate = {
L"PowerToys.PowerLauncher.exe", L"PowerToys.PowerLauncher.exe",
L"PowerToys.Settings.exe", L"PowerToys.Settings.exe",
L"PowerToys.Awake.exe", L"PowerToys.Awake.exe",
@ -1032,6 +1032,7 @@ UINT __stdcall TerminateProcessesCA(MSIHANDLE hInstall)
L"PowerToys.MouseWithoutBorders.exe", L"PowerToys.MouseWithoutBorders.exe",
L"PowerToys.MouseWithoutBordersHelper.exe", L"PowerToys.MouseWithoutBordersHelper.exe",
L"PowerToys.MouseWithoutBordersService.exe", L"PowerToys.MouseWithoutBordersService.exe",
L"PowerToys.CropAndLock.exe",
L"PowerToys.exe", L"PowerToys.exe",
}; };

View File

@ -16,6 +16,10 @@ namespace winrt::PowerToys::GPOWrapper::implementation
{ {
return static_cast<GpoRuleConfigured>(powertoys_gpo::getConfiguredColorPickerEnabledValue()); return static_cast<GpoRuleConfigured>(powertoys_gpo::getConfiguredColorPickerEnabledValue());
} }
GpoRuleConfigured GPOWrapper::GetConfiguredCropAndLockEnabledValue()
{
return static_cast<GpoRuleConfigured>(powertoys_gpo::getConfiguredCropAndLockEnabledValue());
}
GpoRuleConfigured GPOWrapper::GetConfiguredFancyZonesEnabledValue() GpoRuleConfigured GPOWrapper::GetConfiguredFancyZonesEnabledValue()
{ {
return static_cast<GpoRuleConfigured>(powertoys_gpo::getConfiguredFancyZonesEnabledValue()); return static_cast<GpoRuleConfigured>(powertoys_gpo::getConfiguredFancyZonesEnabledValue());

View File

@ -10,6 +10,7 @@ namespace winrt::PowerToys::GPOWrapper::implementation
static GpoRuleConfigured GetConfiguredAlwaysOnTopEnabledValue(); static GpoRuleConfigured GetConfiguredAlwaysOnTopEnabledValue();
static GpoRuleConfigured GetConfiguredAwakeEnabledValue(); static GpoRuleConfigured GetConfiguredAwakeEnabledValue();
static GpoRuleConfigured GetConfiguredColorPickerEnabledValue(); static GpoRuleConfigured GetConfiguredColorPickerEnabledValue();
static GpoRuleConfigured GetConfiguredCropAndLockEnabledValue();
static GpoRuleConfigured GetConfiguredFancyZonesEnabledValue(); static GpoRuleConfigured GetConfiguredFancyZonesEnabledValue();
static GpoRuleConfigured GetConfiguredFileLocksmithEnabledValue(); static GpoRuleConfigured GetConfiguredFileLocksmithEnabledValue();
static GpoRuleConfigured GetConfiguredSvgPreviewEnabledValue(); static GpoRuleConfigured GetConfiguredSvgPreviewEnabledValue();

View File

@ -14,6 +14,7 @@ namespace PowerToys
static GpoRuleConfigured GetConfiguredAlwaysOnTopEnabledValue(); static GpoRuleConfigured GetConfiguredAlwaysOnTopEnabledValue();
static GpoRuleConfigured GetConfiguredAwakeEnabledValue(); static GpoRuleConfigured GetConfiguredAwakeEnabledValue();
static GpoRuleConfigured GetConfiguredColorPickerEnabledValue(); static GpoRuleConfigured GetConfiguredColorPickerEnabledValue();
static GpoRuleConfigured GetConfiguredCropAndLockEnabledValue();
static GpoRuleConfigured GetConfiguredFancyZonesEnabledValue(); static GpoRuleConfigured GetConfiguredFancyZonesEnabledValue();
static GpoRuleConfigured GetConfiguredFileLocksmithEnabledValue(); static GpoRuleConfigured GetConfiguredFileLocksmithEnabledValue();
static GpoRuleConfigured GetConfiguredSvgPreviewEnabledValue(); static GpoRuleConfigured GetConfiguredSvgPreviewEnabledValue();

View File

@ -74,6 +74,11 @@ namespace CommonSharedConstants
// Path to the event used to show Peek // Path to the event used to show Peek
const wchar_t SHOW_PEEK_SHARED_EVENT[] = L"Local\\ShowPeekEvent"; const wchar_t SHOW_PEEK_SHARED_EVENT[] = L"Local\\ShowPeekEvent";
// Path to the events used by CropAndLock
const wchar_t CROP_AND_LOCK_REPARENT_EVENT[] = L"Local\\PowerToysCropAndLockReparentEvent-6060860a-76a1-44e8-8d0e-6355785e9c36";
const wchar_t CROP_AND_LOCK_THUMBNAIL_EVENT[] = L"Local\\PowerToysCropAndLockThumbnailEvent-1637be50-da72-46b2-9220-b32b206b2434";
const wchar_t CROP_AND_LOCK_EXIT_EVENT[] = L"Local\\PowerToysCropAndLockExitEvent-d995d409-7b70-482b-bad6-e7c8666f375a";
// Max DWORD for key code to disable keys. // Max DWORD for key code to disable keys.
const DWORD VK_DISABLED = 0x100; const DWORD VK_DISABLED = 0x100;
} }

View File

@ -59,7 +59,8 @@ struct LogSettings
inline const static std::wstring alwaysOnTopLogPath = L"always-on-top-log.txt"; inline const static std::wstring alwaysOnTopLogPath = L"always-on-top-log.txt";
inline const static std::string hostsLoggerName = "hosts"; inline const static std::string hostsLoggerName = "hosts";
inline const static std::wstring hostsLogPath = L"Logs\\hosts-log.txt"; inline const static std::wstring hostsLogPath = L"Logs\\hosts-log.txt";
inline const static std::string registryPreviewLoggerName = "registrypreview"; inline const static std::string registryPreviewLoggerName = "registrypreview";
inline const static std::string cropAndLockLoggerName = "crop-and-lock";
inline const static std::wstring registryPreviewLogPath = L"Logs\\registryPreview-log.txt"; inline const static std::wstring registryPreviewLogPath = L"Logs\\registryPreview-log.txt";
inline const static int retention = 30; inline const static int retention = 30;
std::wstring logLevel; std::wstring logLevel;

View File

@ -22,6 +22,7 @@ namespace powertoys_gpo {
const std::wstring POLICY_CONFIGURE_ENABLED_ALWAYS_ON_TOP = L"ConfigureEnabledUtilityAlwaysOnTop"; const std::wstring POLICY_CONFIGURE_ENABLED_ALWAYS_ON_TOP = L"ConfigureEnabledUtilityAlwaysOnTop";
const std::wstring POLICY_CONFIGURE_ENABLED_AWAKE = L"ConfigureEnabledUtilityAwake"; const std::wstring POLICY_CONFIGURE_ENABLED_AWAKE = L"ConfigureEnabledUtilityAwake";
const std::wstring POLICY_CONFIGURE_ENABLED_COLOR_PICKER = L"ConfigureEnabledUtilityColorPicker"; const std::wstring POLICY_CONFIGURE_ENABLED_COLOR_PICKER = L"ConfigureEnabledUtilityColorPicker";
const std::wstring POLICY_CONFIGURE_ENABLED_CROP_AND_LOCK = L"ConfigureEnabledUtilityCropAndLock";
const std::wstring POLICY_CONFIGURE_ENABLED_FANCYZONES = L"ConfigureEnabledUtilityFancyZones"; const std::wstring POLICY_CONFIGURE_ENABLED_FANCYZONES = L"ConfigureEnabledUtilityFancyZones";
const std::wstring POLICY_CONFIGURE_ENABLED_FILE_LOCKSMITH = L"ConfigureEnabledUtilityFileLocksmith"; const std::wstring POLICY_CONFIGURE_ENABLED_FILE_LOCKSMITH = L"ConfigureEnabledUtilityFileLocksmith";
const std::wstring POLICY_CONFIGURE_ENABLED_SVG_PREVIEW = L"ConfigureEnabledUtilityFileExplorerSVGPreview"; const std::wstring POLICY_CONFIGURE_ENABLED_SVG_PREVIEW = L"ConfigureEnabledUtilityFileExplorerSVGPreview";
@ -129,6 +130,11 @@ namespace powertoys_gpo {
return getConfiguredValue(POLICY_CONFIGURE_ENABLED_COLOR_PICKER); return getConfiguredValue(POLICY_CONFIGURE_ENABLED_COLOR_PICKER);
} }
inline gpo_rule_configured_t getConfiguredCropAndLockEnabledValue()
{
return getConfiguredValue(POLICY_CONFIGURE_ENABLED_CROP_AND_LOCK);
}
inline gpo_rule_configured_t getConfiguredFancyZonesEnabledValue() inline gpo_rule_configured_t getConfiguredFancyZonesEnabledValue()
{ {
return getConfiguredValue(POLICY_CONFIGURE_ENABLED_FANCYZONES); return getConfiguredValue(POLICY_CONFIGURE_ENABLED_FANCYZONES);

View File

@ -1,17 +1,18 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft Corporation. <!-- Copyright (c) Microsoft Corporation.
Licensed under the MIT License. --> Licensed under the MIT License. -->
<policyDefinitions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" revision="1.2" schemaVersion="1.0" xmlns="http://schemas.microsoft.com/GroupPolicy/2006/07/PolicyDefinitions"> <policyDefinitions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" revision="1.3" schemaVersion="1.0" xmlns="http://schemas.microsoft.com/GroupPolicy/2006/07/PolicyDefinitions">
<policyNamespaces> <policyNamespaces>
<target prefix="powertoys" namespace="Microsoft.Policies.PowerToys" /> <target prefix="powertoys" namespace="Microsoft.Policies.PowerToys" />
</policyNamespaces> </policyNamespaces>
<resources minRequiredRevision="1.2"/><!-- Last changed with PowerToys v0.70.0 --> <resources minRequiredRevision="1.3"/><!-- Last changed with PowerToys v0.73.0 -->
<supportedOn> <supportedOn>
<definitions> <definitions>
<definition name="SUPPORTED_POWERTOYS_0_64_0" displayName="$(string.SUPPORTED_POWERTOYS_0_64_0)"/> <definition name="SUPPORTED_POWERTOYS_0_64_0" displayName="$(string.SUPPORTED_POWERTOYS_0_64_0)"/>
<definition name="SUPPORTED_POWERTOYS_0_68_0" displayName="$(string.SUPPORTED_POWERTOYS_0_68_0)"/> <definition name="SUPPORTED_POWERTOYS_0_68_0" displayName="$(string.SUPPORTED_POWERTOYS_0_68_0)"/>
<definition name="SUPPORTED_POWERTOYS_0_69_0" displayName="$(string.SUPPORTED_POWERTOYS_0_69_0)"/> <definition name="SUPPORTED_POWERTOYS_0_69_0" displayName="$(string.SUPPORTED_POWERTOYS_0_69_0)"/>
<definition name="SUPPORTED_POWERTOYS_0_70_0" displayName="$(string.SUPPORTED_POWERTOYS_0_70_0)"/> <definition name="SUPPORTED_POWERTOYS_0_70_0" displayName="$(string.SUPPORTED_POWERTOYS_0_70_0)"/>
<definition name="SUPPORTED_POWERTOYS_0_73_0" displayName="$(string.SUPPORTED_POWERTOYS_0_73_0)"/>
</definitions> </definitions>
</supportedOn> </supportedOn>
<categories> <categories>
@ -51,6 +52,16 @@
<decimal value="0" /> <decimal value="0" />
</disabledValue> </disabledValue>
</policy> </policy>
<policy name="ConfigureEnabledUtilityCropAndLock" class="Both" displayName="$(string.ConfigureEnabledUtilityCropAndLock)" explainText="$(string.ConfigureEnabledUtilityDescription)" key="Software\Policies\PowerToys" valueName="ConfigureEnabledUtilityCropAndLock">
<parentCategory ref="PowerToys" />
<supportedOn ref="SUPPORTED_POWERTOYS_0_73_0" />
<enabledValue>
<decimal value="1" />
</enabledValue>
<disabledValue>
<decimal value="0" />
</disabledValue>
</policy>
<policy name="ConfigureEnabledUtilityFancyZones" class="Both" displayName="$(string.ConfigureEnabledUtilityFancyZones)" explainText="$(string.ConfigureEnabledUtilityDescription)" key="Software\Policies\PowerToys" valueName="ConfigureEnabledUtilityFancyZones"> <policy name="ConfigureEnabledUtilityFancyZones" class="Both" displayName="$(string.ConfigureEnabledUtilityFancyZones)" explainText="$(string.ConfigureEnabledUtilityDescription)" key="Software\Policies\PowerToys" valueName="ConfigureEnabledUtilityFancyZones">
<parentCategory ref="PowerToys" /> <parentCategory ref="PowerToys" />
<supportedOn ref="SUPPORTED_POWERTOYS_0_64_0" /> <supportedOn ref="SUPPORTED_POWERTOYS_0_64_0" />

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft Corporation. <!-- Copyright (c) Microsoft Corporation.
Licensed under the MIT License. --> Licensed under the MIT License. -->
<policyDefinitionResources xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" revision="1.2" schemaVersion="1.0" xmlns="http://schemas.microsoft.com/GroupPolicy/2006/07/PolicyDefinitions"> <policyDefinitionResources xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" revision="1.3" schemaVersion="1.0" xmlns="http://schemas.microsoft.com/GroupPolicy/2006/07/PolicyDefinitions">
<displayName>PowerToys</displayName> <displayName>PowerToys</displayName>
<description>PowerToys</description> <description>PowerToys</description>
<resources> <resources>
@ -13,6 +13,7 @@
<string id="SUPPORTED_POWERTOYS_0_68_0">PowerToys version 0.68.0 or later</string> <string id="SUPPORTED_POWERTOYS_0_68_0">PowerToys version 0.68.0 or later</string>
<string id="SUPPORTED_POWERTOYS_0_69_0">PowerToys version 0.69.0 or later</string> <string id="SUPPORTED_POWERTOYS_0_69_0">PowerToys version 0.69.0 or later</string>
<string id="SUPPORTED_POWERTOYS_0_70_0">PowerToys version 0.70.0 or later</string> <string id="SUPPORTED_POWERTOYS_0_70_0">PowerToys version 0.70.0 or later</string>
<string id="SUPPORTED_POWERTOYS_0_73_0">PowerToys version 0.73.0 or later</string>
<string id="ConfigureEnabledUtilityDescription">This policy configures the enabled state for a PowerToys utility. <string id="ConfigureEnabledUtilityDescription">This policy configures the enabled state for a PowerToys utility.
@ -67,6 +68,7 @@ If this setting is disabled, experimentation is not allowed.
<string id="ConfigureEnabledUtilityAlwaysOnTop">Always On Top: Configure enabled state</string> <string id="ConfigureEnabledUtilityAlwaysOnTop">Always On Top: Configure enabled state</string>
<string id="ConfigureEnabledUtilityAwake">Awake: Configure enabled state</string> <string id="ConfigureEnabledUtilityAwake">Awake: Configure enabled state</string>
<string id="ConfigureEnabledUtilityColorPicker">Color Picker: Configure enabled state</string> <string id="ConfigureEnabledUtilityColorPicker">Color Picker: Configure enabled state</string>
<string id="ConfigureEnabledUtilityCropAndLock">Crop And Lock: Configure enabled state</string>
<string id="ConfigureEnabledUtilityFancyZones">FancyZones: Configure enabled state</string> <string id="ConfigureEnabledUtilityFancyZones">FancyZones: Configure enabled state</string>
<string id="ConfigureEnabledUtilityFileLocksmith">File Locksmith: Configure enabled state</string> <string id="ConfigureEnabledUtilityFileLocksmith">File Locksmith: Configure enabled state</string>
<string id="ConfigureEnabledUtilityFileExplorerSVGPreview">SVG file preview: Configure enabled state</string> <string id="ConfigureEnabledUtilityFileExplorerSVGPreview">SVG file preview: Configure enabled state</string>

View File

@ -0,0 +1,56 @@
#include "pch.h"
#include "ChildWindow.h"
namespace util
{
using namespace robmikh::common::desktop;
using namespace robmikh::common::desktop::controls;
}
const std::wstring ChildWindow::ClassName = L"CropAndLock.ChildWindow";
std::once_flag ChildWindowClassRegistration;
void ChildWindow::RegisterWindowClass()
{
auto instance = winrt::check_pointer(GetModuleHandleW(nullptr));
WNDCLASSEXW wcex = {};
wcex.cbSize = sizeof(wcex);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = instance;
wcex.hIcon = LoadIconW(instance, IDI_APPLICATION);
wcex.hCursor = LoadCursorW(nullptr, IDC_ARROW);
wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
wcex.lpszClassName = ClassName.c_str();
wcex.hIconSm = LoadIconW(wcex.hInstance, IDI_APPLICATION);
winrt::check_bool(RegisterClassExW(&wcex));
}
ChildWindow::ChildWindow(int width, int height, HWND parent)
{
auto instance = winrt::check_pointer(GetModuleHandleW(nullptr));
std::call_once(ChildWindowClassRegistration, []() { RegisterWindowClass(); });
auto exStyle = 0;
auto style = WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
winrt::check_bool(CreateWindowExW(exStyle, ClassName.c_str(), L"", style,
0, 0, width, height, parent, nullptr, instance, this));
WINRT_ASSERT(m_window);
ShowWindow(m_window, SW_SHOW);
UpdateWindow(m_window);
}
LRESULT ChildWindow::MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam)
{
switch (message)
{
case WM_DESTROY:
break;
default:
return base_type::MessageHandler(message, wparam, lparam);
}
return 0;
}

View File

@ -0,0 +1,11 @@
#pragma once
#include <robmikh.common/DesktopWindow.h>
struct ChildWindow : robmikh::common::desktop::DesktopWindow<ChildWindow>
{
static const std::wstring ClassName;
ChildWindow(int width, int height, HWND parent);
LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam);
private:
static void RegisterWindowClass();
};

View File

@ -0,0 +1,105 @@
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#include "../../../common/version/version.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
1 VERSIONINFO
FILEVERSION FILE_VERSION
PRODUCTVERSION PRODUCT_VERSION
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
#ifdef _DEBUG
FILEFLAGS VS_FF_DEBUG
#else
FILEFLAGS 0x0L
#endif
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_DLL
FILESUBTYPE VFT2_UNKNOWN
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0" // US English (0x0409), Unicode (0x04B0) charset
BEGIN
VALUE "CompanyName", COMPANY_NAME
VALUE "FileDescription", FILE_DESCRIPTION
VALUE "FileVersion", FILE_VERSION_STRING
VALUE "InternalName", INTERNAL_NAME
VALUE "LegalCopyright", COPYRIGHT_NOTE
VALUE "OriginalFilename", ORIGINAL_FILENAME
VALUE "ProductName", PRODUCT_NAME
VALUE "ProductVersion", PRODUCT_VERSION_STRING
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200 // US English (0x0409), Unicode (1200) charset
END
END
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_ICON1 ICON "icon1.ico"
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

View File

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.props" Condition="Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.props')" />
<PropertyGroup Label="Globals">
<CppWinRTOptimized>true</CppWinRTOptimized>
<CppWinRTRootNamespaceAutoMerge>true</CppWinRTRootNamespaceAutoMerge>
<CppWinRTGenerateWindowsMetadata>true</CppWinRTGenerateWindowsMetadata>
<MinimalCoreWin>true</MinimalCoreWin>
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{f5e1146e-b7b3-4e11-85fd-270a500bd78c}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>CropAndLock</RootNamespace>
<WindowsTargetPlatformVersion Condition=" '$(WindowsTargetPlatformVersion)' == '' ">10.0.20348.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.19041.0</WindowsTargetPlatformMinVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM64">
<Configuration>Debug</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM64">
<Configuration>Release</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v143</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '16.0'">v142</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '17.0'">v143</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)' == '18.0'">v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>Spectre</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
<UseDebugLibraries>true</UseDebugLibraries>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets">
<Import Project="PropertySheet.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<TargetName>PowerToys.$(MSBuildProjectName)</TargetName>
<OutDir>..\..\..\..\$(Platform)\$(Configuration)\</OutDir>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PreprocessorDefinitions>_CONSOLE;WINRT_LEAN_AND_MEAN;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<WarningLevel>Level4</WarningLevel>
<AdditionalOptions>%(AdditionalOptions) /bigobj</AdditionalOptions>
<AdditionalIncludeDirectories>$(SolutionDir)src\common\Telemetry;$(SolutionDir)src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<AdditionalDependencies>shell32.lib;dwmapi.lib;DbgHelp.lib;gdi32.lib;Shcore.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">MultiThreadedDebug</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateWindowsMetadata>false</GenerateWindowsMetadata>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<None Include="packages.config" />
<None Include="PropertySheet.props" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="ChildWindow.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="ReparentCropAndLockWindow.cpp" />
<ClCompile Include="ThumbnailCropAndLockWindow.cpp" />
<ClCompile Include="OverlayWindow.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(CIBuild)'!='true'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="trace.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="ChildWindow.h" />
<ClInclude Include="CropAndLockWindow.h" />
<ClInclude Include="DisplaysUtil.h" />
<ClInclude Include="ModuleConstants.h" />
<ClInclude Include="ReparentCropAndLockWindow.h" />
<ClInclude Include="ThumbnailCropAndLockWindow.h" />
<ClInclude Include="SettingsWindow.h" />
<ClInclude Include="OverlayWindow.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="ThumbnailUtil.h" />
<ClInclude Include="trace.h" />
<ClInclude Include="WindowRectUtil.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="CropAndLock.rc" />
</ItemGroup>
<ItemGroup>
<Image Include="icon1.ico" />
</ItemGroup>
<ItemGroup>
<Manifest Include="app.manifest" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\common\logger\logger.vcxproj">
<Project>{d9b8fc84-322a-4f9f-bbb9-20915c47ddfd}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\common\SettingsAPI\SettingsAPI.vcxproj">
<Project>{6955446d-23f7-4023-9bb3-8657f904af99}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<Import Project="..\..\..\..\deps\spdlog.props" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.targets" Condition="Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.targets')" />
<Import Project="..\..\..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220914.1\build\native\Microsoft.Windows.ImplementationLibrary.targets" Condition="Exists('..\..\..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220914.1\build\native\Microsoft.Windows.ImplementationLibrary.targets')" />
<Import Project="..\..\..\..\packages\robmikh.common.0.0.22-beta\build\native\robmikh.common.targets" Condition="Exists('..\..\..\..\packages\robmikh.common.0.0.22-beta\build\native\robmikh.common.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.props'))" />
<Error Condition="!Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.targets'))" />
<Error Condition="!Exists('..\..\..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220914.1\build\native\Microsoft.Windows.ImplementationLibrary.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220914.1\build\native\Microsoft.Windows.ImplementationLibrary.targets'))" />
<Error Condition="!Exists('..\..\..\..\packages\robmikh.common.0.0.22-beta\build\native\robmikh.common.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\..\packages\robmikh.common.0.0.22-beta\build\native\robmikh.common.targets'))" />
</Target>
</Project>

View File

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<None Include="PropertySheet.props" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp" />
<ClCompile Include="pch.cpp" />
<ClCompile Include="ThumbnailCropAndLockWindow.cpp" />
<ClCompile Include="OverlayWindow.cpp" />
<ClCompile Include="ReparentCropAndLockWindow.cpp" />
<ClCompile Include="ChildWindow.cpp" />
<ClCompile Include="trace.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
<ClInclude Include="ThumbnailCropAndLockWindow.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="SettingsWindow.h" />
<ClInclude Include="OverlayWindow.h" />
<ClInclude Include="DisplaysUtil.h" />
<ClInclude Include="ThumbnailUtil.h" />
<ClInclude Include="WindowRectUtil.h" />
<ClInclude Include="CropAndLockWindow.h" />
<ClInclude Include="ReparentCropAndLockWindow.h" />
<ClInclude Include="ChildWindow.h" />
<ClInclude Include="trace.h" />
<ClInclude Include="ModuleConstants.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="CropAndLock.rc" />
</ItemGroup>
<ItemGroup>
<Image Include="icon1.ico" />
</ItemGroup>
<ItemGroup>
<Manifest Include="app.manifest" />
</ItemGroup>
<ItemGroup>
<Natvis Include="$(MSBuildThisFileDirectory)..\..\natvis\wil.natvis" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,10 @@
#pragma once
struct CropAndLockWindow
{
virtual ~CropAndLockWindow() {}
virtual HWND Handle() = 0;
virtual void CropAndLock(HWND windowToCrop, RECT cropRect) = 0;
virtual void OnClosed(std::function<void(HWND)> callback) = 0;
};

View File

@ -0,0 +1,25 @@
#pragma once
inline RECT ComputeAllDisplaysUnion(std::vector<robmikh::common::desktop::DisplayInfo> const& infos)
{
RECT result = {};
result.left = LONG_MAX;
result.top = LONG_MAX;
result.right = LONG_MIN;
result.bottom = LONG_MIN;
for (auto&& info : infos)
{
auto rect = info.Rect();
result.left = std::min(result.left, rect.left);
result.top = std::min(result.top, rect.top);
result.right = std::max(result.right, rect.right);
result.bottom = std::max(result.bottom, rect.bottom);
}
return result;
}
inline RECT ComputeAllDisplaysUnion()
{
auto infos = robmikh::common::desktop::DisplayInfo::GetAllDisplays();
return ComputeAllDisplaysUnion(infos);
}

View File

@ -0,0 +1,6 @@
#pragma once
namespace NonLocalizable
{
const inline wchar_t ModuleKey[] = L"CropAndLock";
}

View File

@ -0,0 +1,356 @@
#include "pch.h"
#include "OverlayWindow.h"
namespace winrt
{
using namespace Windows::UI;
using namespace Windows::UI::Composition;
}
namespace util
{
using namespace robmikh::common::desktop;
}
const std::wstring OverlayWindow::ClassName = L"CropAndLock.OverlayWindow";
const float OverlayWindow::BorderThickness = 5;
std::once_flag OverlayWindowClassRegistration;
bool IsPointWithinRect(POINT const& point, RECT const& rect)
{
return point.x >= rect.left && point.x <= rect.right && point.y >= rect.top && point.y <= rect.bottom;
}
void OverlayWindow::RegisterWindowClass()
{
auto instance = winrt::check_pointer(GetModuleHandleW(nullptr));
WNDCLASSEXW wcex = {};
wcex.cbSize = sizeof(wcex);
wcex.lpfnWndProc = WndProc;
wcex.hInstance = instance;
wcex.hIcon = LoadIconW(instance, IDI_APPLICATION);
wcex.hCursor = LoadCursorW(nullptr, IDC_ARROW);
wcex.lpszClassName = ClassName.c_str();
wcex.hIconSm = LoadIconW(instance, IDI_APPLICATION);
winrt::check_bool(RegisterClassExW(&wcex));
}
OverlayWindow::OverlayWindow(
winrt::Compositor const& compositor,
HWND windowToCrop,
std::function<void(HWND, RECT)> windowCropped)
{
auto instance = winrt::check_pointer(GetModuleHandleW(nullptr));
std::call_once(OverlayWindowClassRegistration, []() { RegisterWindowClass(); });
auto exStyle = WS_EX_NOREDIRECTIONBITMAP | WS_EX_TOOLWINDOW | WS_EX_LAYERED | WS_EX_TOPMOST;
auto style = WS_POPUP;
// Get the union of all displays
auto displaysRect = ComputeAllDisplaysUnion();
// Create our window
winrt::check_bool(CreateWindowExW(exStyle, ClassName.c_str(), L"", style,
displaysRect.left, displaysRect.top, displaysRect.right - displaysRect.left, displaysRect.bottom - displaysRect.top, nullptr, nullptr, instance, this));
WINRT_ASSERT(m_window);
// Load cursors
m_standardCursor.reset(winrt::check_pointer(LoadCursorW(nullptr, IDC_ARROW)));
m_crosshairCursor.reset(winrt::check_pointer(LoadCursorW(nullptr, IDC_CROSS)));
m_cursorType = CursorType::Standard;
// Setup the visual tree
m_compositor = compositor;
m_target = CreateWindowTarget(m_compositor);
m_rootVisual = m_compositor.CreateContainerVisual();
m_shadeVisual = m_compositor.CreateSpriteVisual();
m_windowAreaVisual = m_compositor.CreateContainerVisual();
m_selectionVisual = m_compositor.CreateSpriteVisual();
m_target.Root(m_rootVisual);
auto children = m_rootVisual.Children();
children.InsertAtBottom(m_shadeVisual);
children.InsertAtTop(m_windowAreaVisual);
m_windowAreaVisual.Children().InsertAtTop(m_selectionVisual);
m_rootVisual.RelativeSizeAdjustment({ 1, 1 });
m_shadeBrush = m_compositor.CreateNineGridBrush();
m_shadeBrush.IsCenterHollow(true);
m_shadeBrush.Source(m_compositor.CreateColorBrush(winrt::Color{ 255, 0, 0, 0 }));
m_shadeVisual.Brush(m_shadeBrush);
m_shadeVisual.Opacity(0.6f);
m_shadeVisual.RelativeSizeAdjustment({ 1, 1 });
auto selectionBrush = m_compositor.CreateNineGridBrush();
selectionBrush.SetInsets(BorderThickness);
selectionBrush.IsCenterHollow(true);
selectionBrush.Source(m_compositor.CreateColorBrush(winrt::Color{ 255, 255, 0, 0 }));
m_selectionVisual.Brush(selectionBrush);
WINRT_VERIFY(windowToCrop != nullptr);
m_currentWindow = windowToCrop;
SetupOverlay();
m_windowCropped = windowCropped;
ShowWindow(m_window, SW_SHOW);
UpdateWindow(m_window);
SetForegroundWindow(m_window);
}
void OverlayWindow::SetupOverlay()
{
ResetCrop();
// Get the client bounds of the target window
auto windowBounds = ClientAreaInScreenSpace(m_currentWindow);
// Get the union of all displays
auto displaysRect = ComputeAllDisplaysUnion();
// Before we can use the window bounds, we need to
// shift the origin to the top-left most point.
m_currentWindowAreaBounds.left = windowBounds.left - displaysRect.left;
m_currentWindowAreaBounds.top = windowBounds.top - displaysRect.top;
m_currentWindowAreaBounds.right = m_currentWindowAreaBounds.left + (windowBounds.right - windowBounds.left);
m_currentWindowAreaBounds.bottom = m_currentWindowAreaBounds.top + (windowBounds.bottom - windowBounds.top);
auto windowLeft = static_cast<float>(m_currentWindowAreaBounds.left);
auto windowTop = static_cast<float>(m_currentWindowAreaBounds.top);
auto windowWidth = static_cast<float>(windowBounds.right - windowBounds.left);
auto windowHeight = static_cast<float>(windowBounds.bottom - windowBounds.top);
// Change the shade brush to match the window bounds
// We need to make sure the values are non-negative, as they are invalid insets. We
// can sometimes get negative values for the left and top when windows are maximized.
m_shadeBrush.LeftInset(std::max(windowLeft, 0.0f));
m_shadeBrush.TopInset(std::max(windowTop, 0.0f));
m_shadeBrush.RightInset(std::max(static_cast<float>(displaysRect.right - windowBounds.right), 0.0f));
m_shadeBrush.BottomInset(std::max(static_cast<float>(displaysRect.bottom - windowBounds.bottom), 0.0f));
// Change the window area visual to match the window bounds
m_windowAreaVisual.Offset({ windowLeft, windowTop, 0 });
m_windowAreaVisual.Size({ windowWidth, windowHeight });
// Reset the selection visual
m_selectionVisual.Offset({ 0, 0, 0 });
m_selectionVisual.Size({ 0, 0 });
}
LRESULT OverlayWindow::MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam)
{
switch (message)
{
case WM_DESTROY:
break;
case WM_SETCURSOR:
return OnSetCursor();
case WM_KEYUP:
{
auto key = static_cast<uint32_t>(wparam);
if (key == VK_ESCAPE)
{
DestroyWindow(m_window);
}
}
break;
case WM_LBUTTONDOWN:
{
auto xPos = GET_X_LPARAM(lparam);
auto yPos = GET_Y_LPARAM(lparam);
OnLeftButtonDown(xPos, yPos);
}
break;
case WM_LBUTTONUP:
{
auto xPos = GET_X_LPARAM(lparam);
auto yPos = GET_Y_LPARAM(lparam);
OnLeftButtonUp(xPos, yPos);
}
break;
case WM_MOUSEMOVE:
{
auto xPos = GET_X_LPARAM(lparam);
auto yPos = GET_Y_LPARAM(lparam);
OnMouseMove(xPos, yPos);
}
break;
default:
return base_type::MessageHandler(message, wparam, lparam);
}
return 0;
}
void OverlayWindow::ResetCrop()
{
m_cropStatus = CropStatus::None;
m_startPosition = {};
m_cropRect = {};
}
bool OverlayWindow::OnSetCursor()
{
switch (m_cursorType)
{
case CursorType::Standard:
SetCursor(m_standardCursor.get());
return true;
case CursorType::Crosshair:
SetCursor(m_crosshairCursor.get());
return true;
default:
return false;
}
}
void OverlayWindow::OnLeftButtonDown(int x, int y)
{
if (m_cropStatus == CropStatus::None)
{
if (!IsPointWithinRect({ x, y }, m_currentWindowAreaBounds))
{
DestroyWindow(m_window);
return;
}
m_cropStatus = CropStatus::Ongoing;
x -= m_currentWindowAreaBounds.left;
y -= m_currentWindowAreaBounds.top;
m_selectionVisual.Offset({ x - BorderThickness, y - BorderThickness, 0 });
m_startPosition = { x, y };
}
}
void OverlayWindow::OnLeftButtonUp(int x, int y)
{
if (m_cropStatus == CropStatus::Ongoing)
{
m_cropStatus = CropStatus::Completed;
m_cursorType = CursorType::Standard;
// For debugging, it's easier if the window doesn't block the screen after this point
ShowWindow(m_window, SW_HIDE);
if (x < m_currentWindowAreaBounds.left)
{
x = m_currentWindowAreaBounds.left;
}
else if (x > m_currentWindowAreaBounds.right)
{
x = m_currentWindowAreaBounds.right;
}
if (y < m_currentWindowAreaBounds.top)
{
y = m_currentWindowAreaBounds.top;
}
else if (y > m_currentWindowAreaBounds.bottom)
{
y = m_currentWindowAreaBounds.bottom;
}
x -= m_currentWindowAreaBounds.left;
y -= m_currentWindowAreaBounds.top;
// Compute our crop rect
if (x < m_startPosition.x)
{
m_cropRect.left = x;
m_cropRect.right = m_startPosition.x;
}
else
{
m_cropRect.left = m_startPosition.x;
m_cropRect.right = x;
}
if (y < m_startPosition.y)
{
m_cropRect.top = y;
m_cropRect.bottom = m_startPosition.y;
}
else
{
m_cropRect.top = m_startPosition.y;
m_cropRect.bottom = y;
}
// Exit if the rect is empty
if (m_cropRect.right - m_cropRect.left == 0 || m_cropRect.bottom - m_cropRect.top == 0)
{
DestroyWindow(m_window);
return;
}
// Fire the callback
if (m_windowCropped != nullptr)
{
m_windowCropped(m_currentWindow, m_cropRect);
}
DestroyWindow(m_window);
}
}
void OverlayWindow::OnMouseMove(int x, int y)
{
if (m_cropStatus == CropStatus::None)
{
if (IsPointWithinRect({ x, y }, m_currentWindowAreaBounds))
{
m_cursorType = CursorType::Crosshair;
}
else
{
m_cursorType = CursorType::Standard;
}
}
else if (m_cropStatus == CropStatus::Ongoing)
{
if (x < m_currentWindowAreaBounds.left)
{
x = m_currentWindowAreaBounds.left;
}
else if (x > m_currentWindowAreaBounds.right)
{
x = m_currentWindowAreaBounds.right;
}
if (y < m_currentWindowAreaBounds.top)
{
y = m_currentWindowAreaBounds.top;
}
else if (y > m_currentWindowAreaBounds.bottom)
{
y = m_currentWindowAreaBounds.bottom;
}
x -= m_currentWindowAreaBounds.left;
y -= m_currentWindowAreaBounds.top;
auto offset = m_selectionVisual.Offset();
auto size = m_selectionVisual.Size();
if (x < m_startPosition.x)
{
offset.x = x - BorderThickness;
size.x = (m_startPosition.x - x) + (2 * BorderThickness);
}
else
{
size.x = (x - m_startPosition.x) + (2 * BorderThickness);
}
if (y < m_startPosition.y)
{
offset.y = y - BorderThickness;
size.y = (m_startPosition.y - y) + (2 * BorderThickness);
}
else
{
size.y = (y - m_startPosition.y) + (2 * BorderThickness);
}
m_selectionVisual.Offset(offset);
m_selectionVisual.Size(size);
}
}

View File

@ -0,0 +1,58 @@
#pragma once
#include <robmikh.common/DesktopWindow.h>
struct OverlayWindow : robmikh::common::desktop::DesktopWindow<OverlayWindow>
{
static const std::wstring ClassName;
OverlayWindow(
winrt::Windows::UI::Composition::Compositor const& compositor,
HWND windowToCrop,
std::function<void(HWND, RECT)> windowCropped);
~OverlayWindow() { m_windowCropped = nullptr; DestroyWindow(m_window); }
LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam);
private:
enum class CursorType
{
Standard,
Crosshair,
};
enum class CropStatus
{
None,
Ongoing,
Completed,
};
static const float BorderThickness;
static void RegisterWindowClass();
void SetupOverlay();
void ResetCrop();
bool OnSetCursor();
void OnLeftButtonDown(int x, int y);
void OnLeftButtonUp(int x, int y);
void OnMouseMove(int x, int y);
private:
std::function<void(HWND, RECT)> m_windowCropped;
winrt::Windows::UI::Composition::Compositor m_compositor{ nullptr };
winrt::Windows::UI::Composition::CompositionTarget m_target{ nullptr };
winrt::Windows::UI::Composition::ContainerVisual m_rootVisual{ nullptr };
winrt::Windows::UI::Composition::SpriteVisual m_shadeVisual{ nullptr };
winrt::Windows::UI::Composition::ContainerVisual m_windowAreaVisual{ nullptr };
winrt::Windows::UI::Composition::SpriteVisual m_selectionVisual{ nullptr };
winrt::Windows::UI::Composition::CompositionNineGridBrush m_shadeBrush{ nullptr };
HWND m_currentWindow = nullptr;
RECT m_currentWindowAreaBounds = {};
CropStatus m_cropStatus = CropStatus::None;
POINT m_startPosition = {};
RECT m_cropRect = {};
CursorType m_cursorType = CursorType::Standard;
wil::unique_hcursor m_standardCursor;
wil::unique_hcursor m_crosshairCursor;
};

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros" />
<!--
To customize common C++/WinRT project properties:
* right-click the project node
* expand the Common Properties item
* select the C++/WinRT property page
For more advanced scenarios, and complete documentation, please see:
https://github.com/Microsoft/cppwinrt/tree/master/nuget
-->
<PropertyGroup />
<ItemDefinitionGroup />
</Project>

View File

@ -0,0 +1,160 @@
#include "pch.h"
#include "ReparentCropAndLockWindow.h"
const std::wstring ReparentCropAndLockWindow::ClassName = L"CropAndLock.ReparentCropAndLockWindow";
std::once_flag ReparentCropAndLockWindowClassRegistration;
void ReparentCropAndLockWindow::RegisterWindowClass()
{
auto instance = winrt::check_pointer(GetModuleHandleW(nullptr));
WNDCLASSEXW wcex = {};
wcex.cbSize = sizeof(wcex);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = instance;
wcex.hIcon = LoadIconW(instance, IDI_APPLICATION);
wcex.hCursor = LoadCursorW(nullptr, IDC_ARROW);
wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
wcex.lpszClassName = ClassName.c_str();
wcex.hIconSm = LoadIconW(wcex.hInstance, IDI_APPLICATION);
winrt::check_bool(RegisterClassExW(&wcex));
}
ReparentCropAndLockWindow::ReparentCropAndLockWindow(std::wstring const& titleString, int width, int height)
{
auto instance = winrt::check_pointer(GetModuleHandleW(nullptr));
std::call_once(ReparentCropAndLockWindowClassRegistration, []() { RegisterWindowClass(); });
auto exStyle = 0;
auto style = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN;
style &= ~(WS_MAXIMIZEBOX | WS_THICKFRAME);
RECT rect = { 0, 0, width, height};
winrt::check_bool(AdjustWindowRectEx(&rect, style, false, exStyle));
auto adjustedWidth = rect.right - rect.left;
auto adjustedHeight = rect.bottom - rect.top;
winrt::check_bool(CreateWindowExW(exStyle, ClassName.c_str(), titleString.c_str(), style,
CW_USEDEFAULT, CW_USEDEFAULT, adjustedWidth, adjustedHeight, nullptr, nullptr, instance, this));
WINRT_ASSERT(m_window);
m_childWindow = std::make_unique<ChildWindow>(width, height, m_window);
}
ReparentCropAndLockWindow::~ReparentCropAndLockWindow()
{
DisconnectTarget();
DestroyWindow(m_window);
}
LRESULT ReparentCropAndLockWindow::MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam)
{
switch (message)
{
case WM_DESTROY:
if (m_closedCallback != nullptr && !m_destroyed)
{
m_destroyed = true;
m_closedCallback(m_window);
}
break;
case WM_MOUSEACTIVATE:
if (m_currentTarget != nullptr && GetForegroundWindow() != m_currentTarget)
{
SetForegroundWindow(m_currentTarget);
}
return MA_NOACTIVATE;
case WM_ACTIVATE:
if (static_cast<DWORD>(wparam) == WA_ACTIVE)
{
if (m_currentTarget != nullptr)
{
SetForegroundWindow(m_currentTarget);
}
}
break;
case WM_DPICHANGED:
break;
default:
return base_type::MessageHandler(message, wparam, lparam);
}
return 0;
}
void ReparentCropAndLockWindow::CropAndLock(HWND windowToCrop, RECT cropRect)
{
DisconnectTarget();
m_currentTarget = windowToCrop;
// Adjust the crop rect to be in the window space as reported by win32k
RECT windowRect = {};
winrt::check_bool(GetWindowRect(m_currentTarget, &windowRect));
auto clientRect = ClientAreaInScreenSpace(m_currentTarget);
auto diffX = clientRect.left - windowRect.left;
auto diffY = clientRect.top - windowRect.top;
auto adjustedCropRect = cropRect;
adjustedCropRect.left += diffX;
adjustedCropRect.top += diffY;
adjustedCropRect.right += diffX;
adjustedCropRect.bottom += diffY;
cropRect = adjustedCropRect;
// Save the previous position of the target so that we can restore it.
m_previousPosition = { windowRect.left, windowRect.top };
auto newX = adjustedCropRect.left + windowRect.left;
auto newY = adjustedCropRect.top + windowRect.top;
auto monitor = winrt::check_pointer(MonitorFromWindow(m_currentTarget, MONITOR_DEFAULTTONULL));
uint32_t dpiX = 0;
uint32_t dpiY = 0;
winrt::check_hresult(GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &dpiX, &dpiY));
uint32_t dpi = dpiX > dpiY ? dpiX : dpiY;
// Reconfigure our window
auto width = cropRect.right - cropRect.left;
auto height = cropRect.bottom - cropRect.top;
windowRect = { newX, newY, newX + width, newY + height };
auto exStyle = static_cast<DWORD>(GetWindowLongPtrW(m_window, GWL_EXSTYLE));
auto style = static_cast<DWORD>(GetWindowLongPtrW(m_window, GWL_STYLE));
winrt::check_bool(AdjustWindowRectExForDpi(&windowRect, style, false, exStyle, dpi));
auto adjustedWidth = windowRect.right - windowRect.left;
auto adjustedHeight = windowRect.bottom - windowRect.top;
winrt::check_bool(SetWindowPos(m_window, HWND_TOPMOST, windowRect.left, windowRect.top, adjustedWidth, adjustedHeight, SWP_SHOWWINDOW | SWP_NOACTIVATE));
winrt::check_bool(SetWindowPos(m_childWindow->m_window, nullptr, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE));
// Reparent the target window
SetParent(m_currentTarget, m_childWindow->m_window);
auto targetStyle = GetWindowLongPtrW(m_currentTarget, GWL_STYLE);
targetStyle |= WS_CHILD;
SetWindowLongPtrW(m_currentTarget, GWL_STYLE, targetStyle);
auto x = -cropRect.left;
auto y = -cropRect.top;
winrt::check_bool(SetWindowPos(m_currentTarget, nullptr, x, y, 0, 0, SWP_NOSIZE | SWP_FRAMECHANGED | SWP_NOZORDER));
}
void ReparentCropAndLockWindow::Hide()
{
DisconnectTarget();
ShowWindow(m_window, SW_HIDE);
}
void ReparentCropAndLockWindow::DisconnectTarget()
{
if (m_currentTarget != nullptr)
{
if (!IsWindow(m_currentTarget))
{
// The child window was closed by other means?
m_currentTarget = nullptr;
return;
}
winrt::check_bool(SetWindowPos(m_currentTarget, nullptr, m_previousPosition.x, m_previousPosition.y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_FRAMECHANGED));
SetParent(m_currentTarget, nullptr);
auto targetStyle = static_cast<DWORD>(GetWindowLongPtrW(m_currentTarget, GWL_STYLE));
targetStyle &= ~WS_CHILD;
SetWindowLongPtrW(m_currentTarget, GWL_STYLE, targetStyle);
m_currentTarget = nullptr;
}
}

View File

@ -0,0 +1,29 @@
#pragma once
#include <robmikh.common/DesktopWindow.h>
#include "CropAndLockWindow.h"
#include "ChildWindow.h"
struct ReparentCropAndLockWindow : robmikh::common::desktop::DesktopWindow<ReparentCropAndLockWindow>, CropAndLockWindow
{
static const std::wstring ClassName;
ReparentCropAndLockWindow(std::wstring const& titleString, int width, int height);
~ReparentCropAndLockWindow() override;
LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam);
HWND Handle() override { return m_window; }
void CropAndLock(HWND windowToCrop, RECT cropRect) override;
void OnClosed(std::function<void(HWND)> callback) override { m_closedCallback = callback; }
private:
static void RegisterWindowClass();
void Hide();
void DisconnectTarget();
private:
HWND m_currentTarget = nullptr;
POINT m_previousPosition = {};
std::unique_ptr<ChildWindow> m_childWindow;
bool m_destroyed = false;
std::function<void(HWND)> m_closedCallback;
};

View File

@ -0,0 +1,7 @@
#pragma once
enum class CropAndLockType
{
Reparent,
Thumbnail,
};

View File

@ -0,0 +1,181 @@
#include "pch.h"
#include "ThumbnailCropAndLockWindow.h"
const std::wstring ThumbnailCropAndLockWindow::ClassName = L"CropAndLock.ThumbnailCropAndLockWindow";
std::once_flag ThumbnailCropAndLockWindowClassRegistration;
float ComputeScaleFactor(RECT const& windowRect, RECT const& contentRect)
{
auto windowWidth = static_cast<float>(windowRect.right - windowRect.left);
auto windowHeight = static_cast<float>(windowRect.bottom - windowRect.top);
auto contentWidth = static_cast<float>(contentRect.right - contentRect.left);
auto contentHeight = static_cast<float>(contentRect.bottom - contentRect.top);
auto windowRatio = windowWidth / windowHeight;
auto contentRatio = contentWidth / contentHeight;
auto scaleFactor = windowWidth / contentWidth;
if (windowRatio > contentRatio)
{
scaleFactor = windowHeight / contentHeight;
}
return scaleFactor;
}
RECT ComputeDestRect(RECT const& windowRect, RECT const& contentRect)
{
auto scaleFactor = ComputeScaleFactor(windowRect, contentRect);
auto windowWidth = static_cast<float>(windowRect.right - windowRect.left);
auto windowHeight = static_cast<float>(windowRect.bottom - windowRect.top);
auto contentWidth = static_cast<float>(contentRect.right - contentRect.left) * scaleFactor;
auto contentHeight = static_cast<float>(contentRect.bottom - contentRect.top) * scaleFactor;
auto remainingWidth = windowWidth - contentWidth;
auto remainingHeight = windowHeight - contentHeight;
auto left = static_cast<LONG>(remainingWidth / 2.0f);
auto top = static_cast<LONG>(remainingHeight / 2.0f);
auto right = left + static_cast<LONG>(contentWidth);
auto bottom = top + static_cast<LONG>(contentHeight);
return RECT{ left, top, right, bottom };
}
void ThumbnailCropAndLockWindow::RegisterWindowClass()
{
auto instance = winrt::check_pointer(GetModuleHandleW(nullptr));
WNDCLASSEXW wcex = {};
wcex.cbSize = sizeof(wcex);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = instance;
wcex.hIcon = LoadIconW(instance, IDI_APPLICATION);
wcex.hCursor = LoadCursorW(nullptr, IDC_ARROW);
wcex.hbrBackground = static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH));
wcex.lpszClassName = ClassName.c_str();
wcex.hIconSm = LoadIconW(wcex.hInstance, IDI_APPLICATION);
winrt::check_bool(RegisterClassExW(&wcex));
}
ThumbnailCropAndLockWindow::ThumbnailCropAndLockWindow(std::wstring const& titleString, int width, int height)
{
auto instance = winrt::check_pointer(GetModuleHandleW(nullptr));
std::call_once(ThumbnailCropAndLockWindowClassRegistration, []() { RegisterWindowClass(); });
auto exStyle = 0;
auto style = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN;
RECT rect = { 0, 0, width, height};
winrt::check_bool(AdjustWindowRectEx(&rect, style, false, exStyle));
auto adjustedWidth = rect.right - rect.left;
auto adjustedHeight = rect.bottom - rect.top;
winrt::check_bool(CreateWindowExW(exStyle, ClassName.c_str(), titleString.c_str(), style,
CW_USEDEFAULT, CW_USEDEFAULT, adjustedWidth, adjustedHeight, nullptr, nullptr, instance, this));
WINRT_ASSERT(m_window);
}
ThumbnailCropAndLockWindow::~ThumbnailCropAndLockWindow()
{
DisconnectTarget();
DestroyWindow(m_window);
}
LRESULT ThumbnailCropAndLockWindow::MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam)
{
switch (message)
{
case WM_DESTROY:
if (m_closedCallback != nullptr && !m_destroyed)
{
m_destroyed = true;
m_closedCallback(m_window);
}
break;
case WM_SIZE:
case WM_SIZING:
{
if (m_thumbnail != nullptr)
{
RECT clientRect = {};
winrt::check_bool(GetClientRect(m_window, &clientRect));
m_destRect = ComputeDestRect(clientRect, m_sourceRect);
DWM_THUMBNAIL_PROPERTIES properties = {};
properties.dwFlags = DWM_TNP_RECTDESTINATION;
properties.rcDestination = m_destRect;
winrt::check_hresult(DwmUpdateThumbnailProperties(m_thumbnail.get(), &properties));
}
}
break;
default:
return base_type::MessageHandler(message, wparam, lparam);
}
return 0;
}
void ThumbnailCropAndLockWindow::CropAndLock(HWND windowToCrop, RECT cropRect)
{
DisconnectTarget();
m_currentTarget = windowToCrop;
// Adjust the crop rect to be in the window space as reported by the DWM
RECT windowRect = {};
winrt::check_hresult(DwmGetWindowAttribute(m_currentTarget, DWMWA_EXTENDED_FRAME_BOUNDS, reinterpret_cast<void*>(&windowRect), sizeof(windowRect)));
auto clientRect = ClientAreaInScreenSpace(m_currentTarget);
auto diffX = clientRect.left - windowRect.left;
auto diffY = clientRect.top - windowRect.top;
auto adjustedCropRect = cropRect;
adjustedCropRect.left += diffX;
adjustedCropRect.top += diffY;
adjustedCropRect.right += diffX;
adjustedCropRect.bottom += diffY;
cropRect = adjustedCropRect;
// Resize our window
auto width = cropRect.right - cropRect.left;
auto height = cropRect.bottom - cropRect.top;
windowRect = { 0, 0, width, height };
auto exStyle = static_cast<DWORD>(GetWindowLongPtrW(m_window, GWL_EXSTYLE));
auto style = static_cast<DWORD>(GetWindowLongPtrW(m_window, GWL_STYLE));
winrt::check_bool(AdjustWindowRectEx(&windowRect, style, false, exStyle));
auto adjustedWidth = windowRect.right - windowRect.left;
auto adjustedHeight = windowRect.bottom - windowRect.top;
winrt::check_bool(SetWindowPos(m_window, HWND_TOPMOST, 0, 0, adjustedWidth, adjustedHeight, SWP_NOMOVE | SWP_SHOWWINDOW));
// Setup the thumbnail
winrt::check_hresult(DwmRegisterThumbnail(m_window, m_currentTarget, m_thumbnail.addressof()));
clientRect = {};
winrt::check_bool(GetClientRect(m_window, &clientRect));
m_destRect = clientRect;
m_sourceRect = cropRect;
DWM_THUMBNAIL_PROPERTIES properties = {};
properties.dwFlags = DWM_TNP_SOURCECLIENTAREAONLY | DWM_TNP_VISIBLE | DWM_TNP_OPACITY | DWM_TNP_RECTDESTINATION | DWM_TNP_RECTSOURCE;
properties.fSourceClientAreaOnly = false;
properties.fVisible = true;
properties.opacity = 255;
properties.rcDestination = m_destRect;
properties.rcSource = m_sourceRect;
winrt::check_hresult(DwmUpdateThumbnailProperties(m_thumbnail.get(), &properties));
}
void ThumbnailCropAndLockWindow::Hide()
{
DisconnectTarget();
ShowWindow(m_window, SW_HIDE);
}
void ThumbnailCropAndLockWindow::DisconnectTarget()
{
if (m_currentTarget != nullptr)
{
m_thumbnail.reset();
m_currentTarget = nullptr;
}
}

View File

@ -0,0 +1,32 @@
#pragma once
#include <robmikh.common/DesktopWindow.h>
#include "CropAndLockWindow.h"
struct ThumbnailCropAndLockWindow : robmikh::common::desktop::DesktopWindow<ThumbnailCropAndLockWindow>, CropAndLockWindow
{
static const std::wstring ClassName;
ThumbnailCropAndLockWindow(std::wstring const& titleString, int width, int height);
~ThumbnailCropAndLockWindow() override;
LRESULT MessageHandler(UINT const message, WPARAM const wparam, LPARAM const lparam);
HWND Handle() override { return m_window; }
void CropAndLock(HWND windowToCrop, RECT cropRect) override;
void OnClosed(std::function<void(HWND)> callback) override { m_closedCallback = callback; }
private:
static void RegisterWindowClass();
void Hide();
void DisconnectTarget();
private:
HWND m_currentTarget = nullptr;
POINT m_previousPosition = {};
unique_hthumbnail m_thumbnail;
RECT m_destRect = {};
RECT m_sourceRect = {};
bool m_destroyed = false;
std::function<void(HWND)> m_closedCallback;
};

View File

@ -0,0 +1,3 @@
#pragma once
typedef wil::unique_any<HTHUMBNAIL, decltype(&::DwmUnregisterThumbnail), ::DwmUnregisterThumbnail> unique_hthumbnail;

View File

@ -0,0 +1,14 @@
#pragma once
inline RECT ClientAreaInScreenSpace(HWND window)
{
POINT clientOrigin = { 0, 0 };
winrt::check_bool(ClientToScreen(window, &clientOrigin));
RECT windowBounds = {};
winrt::check_bool(GetClientRect(window, &windowBounds));
windowBounds.left += clientOrigin.x;
windowBounds.top += clientOrigin.y;
windowBounds.right += clientOrigin.x;
windowBounds.bottom += clientOrigin.y;
return windowBounds;
}

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
</assembly>

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

View File

@ -0,0 +1,270 @@
#include "pch.h"
#include "SettingsWindow.h"
#include "OverlayWindow.h"
#include "CropAndLockWindow.h"
#include "ThumbnailCropAndLockWindow.h"
#include "ReparentCropAndLockWindow.h"
#include <common/interop/shared_constants.h>
#include <common/utils/winapi_error.h>
#include <common/utils/logger_helper.h>
#include <common/utils/UnhandledExceptionHandler.h>
#include <common/utils/gpo.h>
#include "ModuleConstants.h"
#include <common/utils/ProcessWaiter.h>
#include "trace.h"
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
namespace winrt
{
using namespace Windows::Foundation;
using namespace Windows::Foundation::Numerics;
using namespace Windows::UI;
using namespace Windows::UI::Composition;
}
namespace util
{
using namespace robmikh::common::desktop;
}
const std::wstring instanceMutexName = L"Local\\PowerToys_CropAndLock_InstanceMutex";
bool m_running = true;
int WINAPI wWinMain(_In_ HINSTANCE, _In_opt_ HINSTANCE, _In_ PWSTR lpCmdLine, _In_ int)
{
// Initialize COM
winrt::init_apartment(winrt::apartment_type::single_threaded);
// Initialize logger automatic logging of exceptions.
LoggerHelpers::init_logger(NonLocalizable::ModuleKey, L"", LogSettings::cropAndLockLoggerName);
InitUnhandledExceptionHandler();
if (powertoys_gpo::getConfiguredCropAndLockEnabledValue() == powertoys_gpo::gpo_rule_configured_disabled)
{
Logger::warn(L"Tried to start with a GPO policy setting the utility to always be disabled. Please contact your systems administrator.");
return 0;
}
// Before we do anything, check to see if we're already running. If we are,
// the hotkey won't register and we'll fail. Instead, we should tell the user
// to kill the other instance and exit this one.
auto mutex = CreateMutex(nullptr, true, instanceMutexName.c_str());
if (mutex == nullptr)
{
Logger::error(L"Failed to create mutex. {}", get_last_error_or_default(GetLastError()));
}
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
// CropAndLock is already open.
return 1;
}
std::wstring pid = std::wstring(lpCmdLine);
if (pid.empty())
{
Logger::warn(L"Tried to run Crop And Lock as a standalone.");
MessageBoxW(nullptr, L"CropAndLock can't run as a standalone. Start it from PowerToys.", L"CropAndLock", MB_ICONERROR);
return 1;
}
auto mainThreadId = GetCurrentThreadId();
ProcessWaiter::OnProcessTerminate(pid, [mainThreadId](int err) {
if (err != ERROR_SUCCESS)
{
Logger::error(L"Failed to wait for parent process exit. {}", get_last_error_or_default(err));
}
else
{
Logger::trace(L"PowerToys runner exited.");
}
Logger::trace(L"Exiting CropAndLock");
PostThreadMessage(mainThreadId, WM_QUIT, 0, 0);
});
// NOTE: reparenting a window with a different DPI context has consequences.
// See https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setparent#remarks
// for more info.
winrt::check_bool(SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2));
// Create the DispatcherQueue that the compositor needs to run
auto controller = util::CreateDispatcherQueueControllerForCurrentThread();
// Setup Composition
auto compositor = winrt::Compositor();
// Create our overlay window
std::unique_ptr<OverlayWindow> overlayWindow;
// Keep a list of our cropped windows
std::vector<std::shared_ptr<CropAndLockWindow>> croppedWindows;
// Handles and thread for the events sent from runner
HANDLE m_reparent_event_handle;
HANDLE m_thumbnail_event_handle;
HANDLE m_exit_event_handle;
std::thread m_event_triggers_thread;
std::function<void(HWND)> removeWindowCallback = [&](HWND windowHandle)
{
if (!m_running)
{
// If we're not running, the reference to croppedWindows might no longer be valid and cause a crash at exit time, due to being called by destructors after wWinMain returns.
return;
}
auto pos = std::find_if(croppedWindows.begin(), croppedWindows.end(), [windowHandle](auto window) { return window->Handle() == windowHandle; });
if (pos != croppedWindows.end())
{
croppedWindows.erase(pos);
}
};
std::function<void(CropAndLockType)> ProcessCommand = [&](CropAndLockType mode)
{
std::function<void(HWND, RECT)> windowCroppedCallback = [&, mode](HWND targetWindow, RECT cropRect) {
auto targetInfo = util::WindowInfo(targetWindow);
// TODO: Fix WindowInfo.h to not contain the null char at the end.
auto nullCharIndex = std::wstring::npos;
do
{
nullCharIndex = targetInfo.Title.rfind(L'\0');
if (nullCharIndex != std::wstring::npos)
{
targetInfo.Title.erase(nullCharIndex);
}
} while (nullCharIndex != std::wstring::npos);
std::wstringstream titleStream;
titleStream << targetInfo.Title << L" (Cropped)";
auto title = titleStream.str();
std::shared_ptr<CropAndLockWindow> croppedWindow;
switch (mode)
{
case CropAndLockType::Reparent:
croppedWindow = std::make_shared<ReparentCropAndLockWindow>(title, 800, 600);
Logger::trace(L"Creating a reparent window");
Trace::CropAndLock::CreateReparentWindow();
break;
case CropAndLockType::Thumbnail:
croppedWindow = std::make_shared<ThumbnailCropAndLockWindow>(title, 800, 600);
Logger::trace(L"Creating a thumbnail window");
Trace::CropAndLock::CreateThumbnailWindow();
break;
default:
return;
}
croppedWindow->CropAndLock(targetWindow, cropRect);
croppedWindow->OnClosed(removeWindowCallback);
croppedWindows.push_back(croppedWindow);
};
overlayWindow.reset();
// Get the current window with focus
auto foregroundWindow = GetForegroundWindow();
if (foregroundWindow != nullptr)
{
bool match = false;
for (auto&& croppedWindow : croppedWindows)
{
if (foregroundWindow == croppedWindow->Handle())
{
match = true;
break;
}
}
if (!match)
{
overlayWindow = std::make_unique<OverlayWindow>(compositor, foregroundWindow, windowCroppedCallback);
}
}
};
// Start a thread to listen on the events.
m_reparent_event_handle = CreateEventW(nullptr, false, false, CommonSharedConstants::CROP_AND_LOCK_REPARENT_EVENT);
m_thumbnail_event_handle = CreateEventW(nullptr, false, false, CommonSharedConstants::CROP_AND_LOCK_THUMBNAIL_EVENT);
m_exit_event_handle = CreateEventW(nullptr, false, false, CommonSharedConstants::CROP_AND_LOCK_EXIT_EVENT);
if (!m_reparent_event_handle || !m_reparent_event_handle || !m_exit_event_handle)
{
Logger::warn(L"Failed to create events. {}", get_last_error_or_default(GetLastError()));
return 1;
}
m_event_triggers_thread = std::thread([&]() {
MSG msg;
HANDLE event_handles[3] = {m_reparent_event_handle, m_thumbnail_event_handle, m_exit_event_handle};
while (m_running)
{
DWORD dwEvt = MsgWaitForMultipleObjects(3, event_handles, false, INFINITE, QS_ALLINPUT);
if (!m_running)
{
break;
}
switch (dwEvt)
{
case WAIT_OBJECT_0:
{
// Reparent Event
bool enqueueSucceeded = controller.DispatcherQueue().TryEnqueue([&]() {
ProcessCommand(CropAndLockType::Reparent);
});
if (!enqueueSucceeded)
{
Logger::error("Couldn't enqueue message to reparent a window.");
}
break;
}
case WAIT_OBJECT_0 + 1:
{
// Thumbnail Event
bool enqueueSucceeded = controller.DispatcherQueue().TryEnqueue([&]() {
ProcessCommand(CropAndLockType::Thumbnail);
});
if (!enqueueSucceeded)
{
Logger::error("Couldn't enqueue message to thumbnail a window.");
}
break;
}
case WAIT_OBJECT_0 + 2:
{
// Exit Event
Logger::trace(L"Received an exit event.");
PostThreadMessage(mainThreadId, WM_QUIT, 0, 0);
break;
}
case WAIT_OBJECT_0 + 3:
if (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
break;
default:
break;
}
}
});
// Message pump
MSG msg = {};
while (GetMessageW(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
m_running = false;
// Needed to unblock MsgWaitForMultipleObjects one last time
SetEvent(m_reparent_event_handle);
CloseHandle(m_reparent_event_handle);
CloseHandle(m_thumbnail_event_handle);
CloseHandle(m_exit_event_handle);
m_event_triggers_thread.join();
return util::ShutdownDispatcherQueueControllerAndWait(controller, static_cast<int>(msg.wParam));
}

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Windows.CppWinRT" version="2.0.220929.3" targetFramework="native" />
<package id="Microsoft.Windows.ImplementationLibrary" version="1.0.220914.1" targetFramework="native" />
<package id="robmikh.common" version="0.0.22-beta" targetFramework="native" />
</packages>

View File

@ -0,0 +1 @@
#include "pch.h"

View File

@ -0,0 +1,78 @@
#pragma once
// Collision from minWinDef min/max and std
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
// Windows
#include <windows.h>
#include <windowsx.h>
// Must come before C++/WinRT
#include <wil/cppwinrt.h>
// WinRT
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Foundation.Numerics.h>
#include <winrt/Windows.System.h>
#include <winrt/Windows.UI.h>
#include <winrt/Windows.UI.Composition.h>
#include <winrt/Windows.UI.Composition.Desktop.h>
#include <winrt/Windows.UI.Popups.h>
#include <winrt/Windows.Graphics.Capture.h>
#include <winrt/Windows.Graphics.DirectX.h>
#include <winrt/Windows.Graphics.DirectX.Direct3d11.h>
// WIL
#include <wil/resource.h>
// DirectX
#include <d3d11_4.h>
#include <dxgi1_6.h>
#include <d2d1_3.h>
#include <wincodec.h>
// DWM
#include <dwmapi.h>
// Shell
#include <shellscalingapi.h>
// STL
#include <vector>
#include <string>
#include <atomic>
#include <memory>
#include <algorithm>
#include <mutex>
#include <sstream>
// robmikh.common
#include <robmikh.common/composition.interop.h>
#include <robmikh.common/direct3d11.interop.h>
#include <robmikh.common/d3dHelpers.h>
#include <robmikh.common/graphics.interop.h>
#include <robmikh.common/dispatcherQueue.desktop.interop.h>
#include <robmikh.common/d3dHelpers.desktop.h>
#include <robmikh.common/composition.desktop.interop.h>
#include <robmikh.common/hwnd.interop.h>
#include <robmikh.common/capture.desktop.interop.h>
#include <robmikh.common/DesktopWindow.h>
#include <robmikh.common/DisplayInfo.h>
#include <robmikh.common/shellHelpers.desktop.h>
#include <robmikh.common/ControlsHelper.h>
#include <robmikh.common/WindowInfo.h>
// Helpers
#include "DisplaysUtil.h"
#include "ThumbnailUtil.h"
#include "WindowRectUtil.h"
// PowerToys
#include <ProjectTelemetry.h>
#include <common/logger/logger.h>
// Application resources
#include "resource.h"
#define MAIN_ICON MAKEINTRESOURCEW(IDI_ICON1)

View File

@ -0,0 +1,26 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by CropAndLock.rc
//
#define IDI_ICON1 101
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
//////////////////////////////
// Non-localizable
#define FILE_DESCRIPTION "PowerToys CropAndLock"
#define INTERNAL_NAME "PowerToys.CropAndLock"
#define ORIGINAL_FILENAME "PowerToys.CropAndLock.exe"
// Non-localizable
//////////////////////////////

View File

@ -0,0 +1,95 @@
#include "pch.h"
#include "trace.h"
// Telemetry strings should not be localized.
#define LoggingProviderKey "Microsoft.PowerToys"
TRACELOGGING_DEFINE_PROVIDER(
g_hProvider,
LoggingProviderKey,
// {38e8889b-9731-53f5-e901-e8a7c1753074}
(0x38e8889b, 0x9731, 0x53f5, 0xe9, 0x01, 0xe8, 0xa7, 0xc1, 0x75, 0x30, 0x74),
TraceLoggingOptionProjectTelemetry());
void Trace::RegisterProvider() noexcept
{
TraceLoggingRegister(g_hProvider);
}
void Trace::UnregisterProvider() noexcept
{
TraceLoggingUnregister(g_hProvider);
}
void Trace::CropAndLock::Enable(bool enabled) noexcept
{
TraceLoggingWrite(
g_hProvider,
"CropAndLock_EnableCropAndLock",
ProjectTelemetryPrivacyDataTag(ProjectTelemetryTag_ProductAndServicePerformance),
TraceLoggingKeyword(PROJECT_KEYWORD_MEASURE),
TraceLoggingBoolean(enabled, "Enabled"));
}
void Trace::CropAndLock::ActivateReparent() noexcept
{
TraceLoggingWrite(
g_hProvider,
"CropAndLock_ActivateReparent",
ProjectTelemetryPrivacyDataTag(ProjectTelemetryTag_ProductAndServicePerformance),
TraceLoggingKeyword(PROJECT_KEYWORD_MEASURE));
}
void Trace::CropAndLock::ActivateThumbnail() noexcept
{
TraceLoggingWrite(
g_hProvider,
"CropAndLock_ActivateThumbnail",
ProjectTelemetryPrivacyDataTag(ProjectTelemetryTag_ProductAndServicePerformance),
TraceLoggingKeyword(PROJECT_KEYWORD_MEASURE));
}
void Trace::CropAndLock::CreateReparentWindow() noexcept
{
TraceLoggingWrite(
g_hProvider,
"CropAndLock_CreateReparentWindow",
ProjectTelemetryPrivacyDataTag(ProjectTelemetryTag_ProductAndServicePerformance),
TraceLoggingKeyword(PROJECT_KEYWORD_MEASURE));
}
void Trace::CropAndLock::CreateThumbnailWindow() noexcept
{
TraceLoggingWrite(
g_hProvider,
"CropAndLock_CreateThumbnailWindow",
ProjectTelemetryPrivacyDataTag(ProjectTelemetryTag_ProductAndServicePerformance),
TraceLoggingKeyword(PROJECT_KEYWORD_MEASURE));
}
// Event to send settings telemetry.
void Trace::CropAndLock::SettingsTelemetry(PowertoyModuleIface::Hotkey& reparentHotkey, PowertoyModuleIface::Hotkey& thumbnailHotkey) noexcept
{
std::wstring hotKeyStrReparent =
std::wstring(reparentHotkey.win ? L"Win + " : L"") +
std::wstring(reparentHotkey.ctrl ? L"Ctrl + " : L"") +
std::wstring(reparentHotkey.shift ? L"Shift + " : L"") +
std::wstring(reparentHotkey.alt ? L"Alt + " : L"") +
std::wstring(L"VK ") + std::to_wstring(reparentHotkey.key);
std::wstring hotKeyStrThumbnail =
std::wstring(thumbnailHotkey.win ? L"Win + " : L"") +
std::wstring(thumbnailHotkey.ctrl ? L"Ctrl + " : L"") +
std::wstring(thumbnailHotkey.shift ? L"Shift + " : L"") +
std::wstring(thumbnailHotkey.alt ? L"Alt + " : L"") +
std::wstring(L"VK ") + std::to_wstring(thumbnailHotkey.key);
TraceLoggingWrite(
g_hProvider,
"CropAndLock_Settings",
ProjectTelemetryPrivacyDataTag(ProjectTelemetryTag_ProductAndServicePerformance),
TraceLoggingKeyword(PROJECT_KEYWORD_MEASURE),
TraceLoggingWideString(hotKeyStrReparent.c_str(), "ReparentHotKey"),
TraceLoggingWideString(hotKeyStrThumbnail.c_str(), "ThumbnailHotkey")
);
}

View File

@ -0,0 +1,20 @@
#pragma once
#include <modules/interface/powertoy_module_interface.h>
class Trace
{
public:
static void RegisterProvider() noexcept;
static void UnregisterProvider() noexcept;
class CropAndLock
{
public:
static void Enable(bool enabled) noexcept;
static void ActivateReparent() noexcept;
static void ActivateThumbnail() noexcept;
static void CreateReparentWindow() noexcept;
static void CreateThumbnailWindow() noexcept;
static void SettingsTelemetry(PowertoyModuleIface::Hotkey&, PowertoyModuleIface::Hotkey&) noexcept;
};
};

View File

@ -0,0 +1,40 @@
#include <windows.h>
#include "resource.h"
#include "../../../common/version/version.h"
#define APSTUDIO_READONLY_SYMBOLS
#include "winres.h"
#undef APSTUDIO_READONLY_SYMBOLS
1 VERSIONINFO
FILEVERSION FILE_VERSION
PRODUCTVERSION PRODUCT_VERSION
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
#ifdef _DEBUG
FILEFLAGS VS_FF_DEBUG
#else
FILEFLAGS 0x0L
#endif
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_DLL
FILESUBTYPE VFT2_UNKNOWN
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0" // US English (0x0409), Unicode (0x04B0) charset
BEGIN
VALUE "CompanyName", COMPANY_NAME
VALUE "FileDescription", FILE_DESCRIPTION
VALUE "FileVersion", FILE_VERSION_STRING
VALUE "InternalName", INTERNAL_NAME
VALUE "LegalCopyright", COPYRIGHT_NOTE
VALUE "OriginalFilename", ORIGINAL_FILENAME
VALUE "ProductName", PRODUCT_NAME
VALUE "ProductVersion", PRODUCT_VERSION_STRING
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200 // US English (0x0409), Unicode (1200) charset
END
END

View File

@ -0,0 +1,118 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.props" Condition="Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.props')" />
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{3157fa75-86cf-4ee2-8f62-c43f776493c6}</ProjectGuid>
<RootNamespace>CropAndLockModuleInterface</RootNamespace>
<ProjectName>CropAndLockModuleInterface</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets">
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<OutDir>..\..\..\..\$(Platform)\$(Configuration)\</OutDir>
<TargetName>PowerToys.CropAndLockModuleInterface</TargetName>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>..\;$(SolutionDir)src\common\Telemetry;$(SolutionDir)src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
<ClCompile>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableUAC>false</EnableUAC>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\CropAndLock\ModuleConstants.h" />
<ClInclude Include="..\CropAndLock\trace.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="resource.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\CropAndLock\trace.cpp" />
<ClCompile Include="dllmain.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(CIBuild)'!='true'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="CropAndLockModuleInterface.rc" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\common\logger\logger.vcxproj">
<Project>{d9b8fc84-322a-4f9f-bbb9-20915c47ddfd}</Project>
</ProjectReference>
<ProjectReference Include="..\..\..\common\SettingsAPI\SettingsAPI.vcxproj">
<Project>{6955446d-23f7-4023-9bb3-8657f904af99}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="..\..\..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.211019.2\build\native\Microsoft.Windows.ImplementationLibrary.targets" Condition="Exists('..\..\..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.211019.2\build\native\Microsoft.Windows.ImplementationLibrary.targets')" />
<Import Project="..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.targets" Condition="Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.targets')" />
<Import Project="..\..\..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220914.1\build\native\Microsoft.Windows.ImplementationLibrary.targets" Condition="Exists('..\..\..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220914.1\build\native\Microsoft.Windows.ImplementationLibrary.targets')" />
<Import Project="..\..\..\..\packages\robmikh.common.0.0.22-beta\build\native\robmikh.common.targets" Condition="Exists('..\..\..\..\packages\robmikh.common.0.0.22-beta\build\native\robmikh.common.targets')" />
</ImportGroup>
<Import Project="..\..\..\..\deps\spdlog.props" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.props'))" />
<Error Condition="!Exists('..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\..\packages\Microsoft.Windows.CppWinRT.2.0.220929.3\build\native\Microsoft.Windows.CppWinRT.targets'))" />
<Error Condition="!Exists('..\..\..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220914.1\build\native\Microsoft.Windows.ImplementationLibrary.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220914.1\build\native\Microsoft.Windows.ImplementationLibrary.targets'))" />
<Error Condition="!Exists('..\..\..\..\packages\robmikh.common.0.0.22-beta\build\native\robmikh.common.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\..\..\packages\robmikh.common.0.0.22-beta\build\native\robmikh.common.targets'))" />
</Target>
</Project>

View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="pch.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\CropAndLock\trace.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\CropAndLock\ModuleConstants.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="resource.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="pch.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\CropAndLock\trace.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="CropAndLockModuleInterface.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Natvis Include="$(MSBuildThisFileDirectory)..\..\natvis\wil.natvis" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,334 @@
#include "pch.h"
#include <modules/interface/powertoy_module_interface.h>
#include <common/SettingsAPI/settings_objects.h>
#include <common/logger/logger.h>
#include <common/utils/logger_helper.h>
#include <common/utils/resources.h>
#include <common/utils/winapi_error.h>
#include <CropAndLock/trace.h>
#include <CropAndLock/ModuleConstants.h>
#include <shellapi.h>
#include <common/interop/shared_constants.h>
namespace NonLocalizable
{
const wchar_t ModulePath[] = L"PowerToys.CropAndLock.exe";
}
namespace
{
const wchar_t JSON_KEY_PROPERTIES[] = L"properties";
const wchar_t JSON_KEY_WIN[] = L"win";
const wchar_t JSON_KEY_ALT[] = L"alt";
const wchar_t JSON_KEY_CTRL[] = L"ctrl";
const wchar_t JSON_KEY_SHIFT[] = L"shift";
const wchar_t JSON_KEY_CODE[] = L"code";
const wchar_t JSON_KEY_REPARENT_HOTKEY[] = L"reparent-hotkey";
const wchar_t JSON_KEY_THUMBNAIL_HOTKEY[] = L"thumbnail-hotkey";
const wchar_t JSON_KEY_VALUE[] = L"value";
}
BOOL APIENTRY DllMain( HMODULE /*hModule*/,
DWORD ul_reason_for_call,
LPVOID /*lpReserved*/
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
Trace::RegisterProvider();
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
Trace::UnregisterProvider();
break;
}
return TRUE;
}
class CropAndLockModuleInterface : public PowertoyModuleIface
{
public:
// Return the localized display name of the powertoy
virtual PCWSTR get_name() override
{
return app_name.c_str();
}
// Return the non localized key of the powertoy, this will be cached by the runner
virtual const wchar_t* get_key() override
{
return app_key.c_str();
}
// Return the configured status for the gpo policy for the module
virtual powertoys_gpo::gpo_rule_configured_t gpo_policy_enabled_configuration() override
{
return powertoys_gpo::getConfiguredCropAndLockEnabledValue();
}
// Return JSON with the configuration options.
// These are the settings shown on the settings page along with their current values.
virtual bool get_config(wchar_t* buffer, int* buffer_size) override
{
HINSTANCE hinstance = reinterpret_cast<HINSTANCE>(&__ImageBase);
// Create a Settings object.
PowerToysSettings::Settings settings(hinstance, get_name());
return settings.serialize_to_buffer(buffer, buffer_size);
}
// Passes JSON with the configuration settings for the powertoy.
// This is called when the user hits Save on the settings page.
virtual void set_config(const wchar_t* config) override
{
try
{
// Parse the input JSON string.
PowerToysSettings::PowerToyValues values =
PowerToysSettings::PowerToyValues::from_json_string(config, get_key());
parse_hotkey(values);
values.save_to_settings_file();
}
catch (std::exception&)
{
// Improper JSON.
}
}
virtual bool on_hotkey(size_t hotkeyId) override
{
if (m_enabled)
{
Logger::trace(L"CropAndLock hotkey pressed");
if (!is_process_running())
{
Enable();
}
if (hotkeyId == 0) { // Same order as set by get_hotkeys
SetEvent(m_reparent_event_handle);
Trace::CropAndLock::ActivateReparent();
}
if (hotkeyId == 1) { // Same order as set by get_hotkeys
SetEvent(m_thumbnail_event_handle);
Trace::CropAndLock::ActivateThumbnail();
}
return true;
}
return false;
}
virtual size_t get_hotkeys(Hotkey* hotkeys, size_t buffer_size) override
{
if (hotkeys && buffer_size >= 2)
{
hotkeys[0] = m_reparent_hotkey;
hotkeys[1] = m_thumbnail_hotkey;
}
return 2;
}
// Enable the powertoy
virtual void enable()
{
Logger::info("CropAndLock enabling");
Enable();
}
// Disable the powertoy
virtual void disable()
{
Logger::info("CropAndLock disabling");
Disable(true);
}
// Returns if the powertoy is enabled
virtual bool is_enabled() override
{
return m_enabled;
}
// Destroy the powertoy and free memory
virtual void destroy() override
{
Disable(false);
delete this;
}
virtual void send_settings_telemetry() override
{
Logger::info("Send settings telemetry");
Trace::CropAndLock::SettingsTelemetry(m_reparent_hotkey, m_thumbnail_hotkey);
}
CropAndLockModuleInterface()
{
app_name = L"CropAndLock";
app_key = NonLocalizable::ModuleKey;
LoggerHelpers::init_logger(app_key, L"ModuleInterface", LogSettings::cropAndLockLoggerName);
m_reparent_event_handle = CreateDefaultEvent(CommonSharedConstants::CROP_AND_LOCK_REPARENT_EVENT);
m_thumbnail_event_handle = CreateDefaultEvent(CommonSharedConstants::CROP_AND_LOCK_THUMBNAIL_EVENT);
m_exit_event_handle = CreateDefaultEvent(CommonSharedConstants::CROP_AND_LOCK_EXIT_EVENT);
init_settings();
}
private:
void Enable()
{
m_enabled = true;
// Log telemetry
Trace::CropAndLock::Enable(true);
// Pass the PID.
unsigned long powertoys_pid = GetCurrentProcessId();
std::wstring executable_args = L"";
executable_args.append(std::to_wstring(powertoys_pid));
ResetEvent(m_reparent_event_handle);
ResetEvent(m_thumbnail_event_handle);
ResetEvent(m_exit_event_handle);
SHELLEXECUTEINFOW sei{ sizeof(sei) };
sei.fMask = { SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI };
sei.lpFile = NonLocalizable::ModulePath;
sei.nShow = SW_SHOWNORMAL;
sei.lpParameters = executable_args.data();
if (ShellExecuteExW(&sei) == false)
{
Logger::error(L"Failed to start CropAndLock");
auto message = get_last_error_message(GetLastError());
if (message.has_value())
{
Logger::error(message.value());
}
}
else
{
m_hProcess = sei.hProcess;
}
}
void Disable(bool const traceEvent)
{
m_enabled = false;
// We can't just kill the process, since Crop and Lock might need to release any reparented windows first.
SetEvent(m_exit_event_handle);
ResetEvent(m_reparent_event_handle);
ResetEvent(m_thumbnail_event_handle);
// Log telemetry
if (traceEvent)
{
Trace::CropAndLock::Enable(false);
}
if (m_hProcess)
{
m_hProcess = nullptr;
}
}
void parse_hotkey(PowerToysSettings::PowerToyValues& settings)
{
auto settingsObject = settings.get_raw_json();
if (settingsObject.GetView().Size())
{
try
{
Hotkey _temp_reparent;
auto jsonHotkeyObject = settingsObject.GetNamedObject(JSON_KEY_PROPERTIES).GetNamedObject(JSON_KEY_REPARENT_HOTKEY).GetNamedObject(JSON_KEY_VALUE);
_temp_reparent.win = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_WIN);
_temp_reparent.alt = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_ALT);
_temp_reparent.shift = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_SHIFT);
_temp_reparent.ctrl = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_CTRL);
_temp_reparent.key = static_cast<unsigned char>(jsonHotkeyObject.GetNamedNumber(JSON_KEY_CODE));
m_reparent_hotkey = _temp_reparent;
}
catch (...)
{
Logger::error("Failed to initialize CropAndLock reparent shortcut from settings. Value will keep unchanged.");
}
try
{
Hotkey _temp_thumbnail;
auto jsonHotkeyObject = settingsObject.GetNamedObject(JSON_KEY_PROPERTIES).GetNamedObject(JSON_KEY_THUMBNAIL_HOTKEY).GetNamedObject(JSON_KEY_VALUE);
_temp_thumbnail.win = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_WIN);
_temp_thumbnail.alt = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_ALT);
_temp_thumbnail.shift = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_SHIFT);
_temp_thumbnail.ctrl = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_CTRL);
_temp_thumbnail.key = static_cast<unsigned char>(jsonHotkeyObject.GetNamedNumber(JSON_KEY_CODE));
m_thumbnail_hotkey = _temp_thumbnail;
}
catch (...)
{
Logger::error("Failed to initialize CropAndLock thumbnail shortcut from settings. Value will keep unchanged.");
}
}
else
{
Logger::info("CropAndLock settings are empty");
}
}
bool is_process_running()
{
return WaitForSingleObject(m_hProcess, 0) == WAIT_TIMEOUT;
}
void init_settings()
{
try
{
// Load and parse the settings file for this PowerToy.
PowerToysSettings::PowerToyValues settings =
PowerToysSettings::PowerToyValues::load_from_settings_file(get_key());
parse_hotkey(settings);
}
catch (std::exception&)
{
Logger::warn(L"An exception occurred while loading the settings file");
// Error while loading from the settings file. Let default values stay as they are.
}
}
std::wstring app_name;
std::wstring app_key; //contains the non localized key of the powertoy
bool m_enabled = false;
HANDLE m_hProcess = nullptr;
// TODO: actual default hotkey setting in line with other PowerToys.
Hotkey m_reparent_hotkey = { .win = true, .ctrl = true, .shift = true, .alt = false, .key = 'R' };
Hotkey m_thumbnail_hotkey = { .win = true, .ctrl = true, .shift = true, .alt = false, .key = 'T' };
HANDLE m_reparent_event_handle;
HANDLE m_thumbnail_event_handle;
HANDLE m_exit_event_handle;
};
extern "C" __declspec(dllexport) PowertoyModuleIface* __cdecl powertoy_create()
{
return new CropAndLockModuleInterface();
}

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Windows.CppWinRT" version="2.0.220929.3" targetFramework="native" />
<package id="Microsoft.Windows.ImplementationLibrary" version="1.0.220914.1" targetFramework="native" />
</packages>

View File

@ -0,0 +1,5 @@
// pch.cpp: source file corresponding to the pre-compiled header
#include "pch.h"
// When you are using pre-compiled headers, this source file is necessary for compilation to succeed.

View File

@ -0,0 +1,12 @@
#pragma once
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <Unknwn.h>
#include <winrt/base.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <ProjectTelemetry.h>
#include <TraceLoggingActivity.h>
#include <wil\common.h>
#include <wil\result.h>

View File

@ -0,0 +1,13 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by CropAndLockModuleInterface.rc
//////////////////////////////
// Non-localizable
#define FILE_DESCRIPTION "PowerToys CropAndLockModuleInterface"
#define INTERNAL_NAME "PowerToys.CropAndLockModuleInterface"
#define ORIGINAL_FILENAME "PowerToys.CropAndLockModuleInterface.dll"
// Non-localizable
//////////////////////////////

View File

@ -52,4 +52,4 @@ void Trace::AlwaysOnTop::UnpinWindow() noexcept
EventUnpinWindowKey, EventUnpinWindowKey,
ProjectTelemetryPrivacyDataTag(ProjectTelemetryTag_ProductAndServicePerformance), ProjectTelemetryPrivacyDataTag(ProjectTelemetryTag_ProductAndServicePerformance),
TraceLoggingKeyword(PROJECT_KEYWORD_MEASURE)); TraceLoggingKeyword(PROJECT_KEYWORD_MEASURE));
} }

View File

@ -156,6 +156,7 @@ int runner(bool isProcessElevated, bool openSettings, std::string settingsWindow
L"WinUI3Apps/PowerToys.HostsModuleInterface.dll", L"WinUI3Apps/PowerToys.HostsModuleInterface.dll",
L"WinUI3Apps/PowerToys.Peek.dll", L"WinUI3Apps/PowerToys.Peek.dll",
L"PowerToys.MouseWithoutBordersModuleInterface.dll", L"PowerToys.MouseWithoutBordersModuleInterface.dll",
L"PowerToys.CropAndLockModuleInterface.dll",
}; };
const auto VCM_PATH = L"PowerToys.VideoConferenceModule.dll"; const auto VCM_PATH = L"PowerToys.VideoConferenceModule.dll";
if (const auto mf = LoadLibraryA("mf.dll")) if (const auto mf = LoadLibraryA("mf.dll"))

View File

@ -0,0 +1,27 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Microsoft.PowerToys.Settings.UI.Library
{
public class CropAndLockProperties
{
public static readonly HotkeySettings DefaultReparentHotkeyValue = new HotkeySettings(true, true, false, true, 0x52); // Ctrl+Win+Shift+R
public static readonly HotkeySettings DefaultThumbnailHotkeyValue = new HotkeySettings(true, true, false, true, 0x54); // Ctrl+Win+Shift+T
public CropAndLockProperties()
{
ReparentHotkey = new KeyboardKeysProperty(DefaultReparentHotkeyValue);
ThumbnailHotkey = new KeyboardKeysProperty(DefaultThumbnailHotkeyValue);
}
[JsonPropertyName("reparent-hotkey")]
public KeyboardKeysProperty ReparentHotkey { get; set; }
[JsonPropertyName("thumbnail-hotkey")]
public KeyboardKeysProperty ThumbnailHotkey { get; set; }
}
}

View File

@ -0,0 +1,35 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text.Json.Serialization;
using Microsoft.PowerToys.Settings.UI.Library.Interfaces;
namespace Microsoft.PowerToys.Settings.UI.Library
{
public class CropAndLockSettings : BasePTModuleSettings, ISettingsConfig
{
public const string ModuleName = "CropAndLock";
public const string ModuleVersion = "0.0.1";
public CropAndLockSettings()
{
Name = ModuleName;
Version = ModuleVersion;
Properties = new CropAndLockProperties();
}
[JsonPropertyName("properties")]
public CropAndLockProperties Properties { get; set; }
public string GetModuleName()
{
return Name;
}
public bool UpgradeSettingsConfiguration()
{
return false;
}
}
}

View File

@ -166,6 +166,23 @@ namespace Microsoft.PowerToys.Settings.UI.Library
} }
} }
private bool cropAndLock = true;
[JsonPropertyName("CropAndLock")]
public bool CropAndLock
{
get => cropAndLock;
set
{
if (cropAndLock != value)
{
LogTelemetryEvent(value);
cropAndLock = value;
NotifyChange();
}
}
}
private bool awake; private bool awake;
[JsonPropertyName("Awake")] [JsonPropertyName("Awake")]

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

View File

@ -10,6 +10,7 @@ namespace Microsoft.PowerToys.Settings.UI.OOBE.Enums
AlwaysOnTop, AlwaysOnTop,
Awake, Awake,
ColorPicker, ColorPicker,
CropAndLock,
FancyZones, FancyZones,
FileLocksmith, FileLocksmith,
FileExplorer, FileExplorer,

View File

@ -97,6 +97,9 @@ namespace Microsoft.PowerToys.Settings.UI
case "ColorPicker": case "ColorPicker":
needToUpdate = generalSettingsConfig.Enabled.ColorPicker != isEnabled; needToUpdate = generalSettingsConfig.Enabled.ColorPicker != isEnabled;
generalSettingsConfig.Enabled.ColorPicker = isEnabled; break; generalSettingsConfig.Enabled.ColorPicker = isEnabled; break;
case "CropAndLock":
needToUpdate = generalSettingsConfig.Enabled.CropAndLock != isEnabled;
generalSettingsConfig.Enabled.CropAndLock = isEnabled; break;
case "FancyZones": case "FancyZones":
needToUpdate = generalSettingsConfig.Enabled.FancyZones != isEnabled; needToUpdate = generalSettingsConfig.Enabled.FancyZones != isEnabled;
generalSettingsConfig.Enabled.FancyZones = isEnabled; break; generalSettingsConfig.Enabled.FancyZones = isEnabled; break;

View File

@ -0,0 +1,47 @@
<Page
x:Class="Microsoft.PowerToys.Settings.UI.OOBE.Views.OobeCropAndLock"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:Microsoft.PowerToys.Settings.UI.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:Microsoft.PowerToys.Settings.UI.OOBE.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:toolkitcontrols="using:CommunityToolkit.WinUI.UI.Controls"
mc:Ignorable="d">
<controls:OOBEPageControl
x:Uid="Oobe_CropAndLock"
HeroImage="ms-appx:///Assets/Settings/Modules/OOBE/CropAndLock.gif">
<controls:OOBEPageControl.PageContent>
<StackPanel Orientation="Vertical">
<TextBlock
x:Uid="Oobe_HowToUse"
Style="{ThemeResource OobeSubtitleStyle}" />
<controls:ShortcutWithTextLabelControl
x:Name="ThumbnailHotkeyControl"
x:Uid="Oobe_CropAndLock_HowToUse_Thumbnail" />
<controls:ShortcutWithTextLabelControl
x:Name="ReparentHotkeyControl"
x:Uid="Oobe_CropAndLock_HowToUse_Reparent" />
<StackPanel
Margin="0,24,0,0"
Orientation="Horizontal"
Spacing="12">
<Button
x:Uid="OOBE_Settings"
Click="SettingsLaunchButton_Click" />
<HyperlinkButton
NavigateUri="https://aka.ms/PowerToysOverview_CropAndLock"
Style="{StaticResource TextButtonStyle}">
<TextBlock
x:Uid="LearnMore_CropAndLock"
TextWrapping="Wrap" />
</HyperlinkButton>
</StackPanel>
</StackPanel>
</controls:OOBEPageControl.PageContent>
</controls:OOBEPageControl>
</Page>

View File

@ -0,0 +1,47 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.PowerToys.Settings.UI.OOBE.Enums;
using Microsoft.PowerToys.Settings.UI.OOBE.ViewModel;
using Microsoft.PowerToys.Settings.UI.Views;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Navigation;
namespace Microsoft.PowerToys.Settings.UI.OOBE.Views
{
public sealed partial class OobeCropAndLock : Page
{
public OobePowerToysModule ViewModel { get; set; }
public OobeCropAndLock()
{
InitializeComponent();
ViewModel = new OobePowerToysModule(OobeShellPage.OobeShellHandler.Modules[(int)PowerToysModules.CropAndLock]);
DataContext = ViewModel;
}
private void SettingsLaunchButton_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
{
if (OobeShellPage.OpenMainWindowCallback != null)
{
OobeShellPage.OpenMainWindowCallback(typeof(CropAndLockPage));
}
ViewModel.LogOpeningSettingsEvent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ViewModel.LogOpeningModuleEvent();
ReparentHotkeyControl.Keys = SettingsRepository<CropAndLockSettings>.GetInstance(new SettingsUtils()).SettingsConfig.Properties.ReparentHotkey.Value.GetKeysList();
ThumbnailHotkeyControl.Keys = SettingsRepository<CropAndLockSettings>.GetInstance(new SettingsUtils()).SettingsConfig.Properties.ThumbnailHotkey.Value.GetKeysList();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
ViewModel.LogClosingModuleEvent();
}
}
}

View File

@ -91,6 +91,10 @@
x:Uid="Shell_ColorPicker" x:Uid="Shell_ColorPicker"
Icon="{ui:BitmapIcon Source=/Assets/Settings/FluentIcons/FluentIconsColorPicker.png}" Icon="{ui:BitmapIcon Source=/Assets/Settings/FluentIcons/FluentIconsColorPicker.png}"
Tag="ColorPicker" /> Tag="ColorPicker" />
<NavigationViewItem
x:Uid="Shell_CropAndLock"
Icon="{ui:BitmapIcon Source=/Assets/Settings/FluentIcons/FluentIconsCropAndLock.png}"
Tag="CropAndLock" />
<NavigationViewItem <NavigationViewItem
x:Uid="Shell_FancyZones" x:Uid="Shell_FancyZones"
Icon="{ui:BitmapIcon Source=/Assets/Settings/FluentIcons/FluentIconsFancyZones.png}" Icon="{ui:BitmapIcon Source=/Assets/Settings/FluentIcons/FluentIconsFancyZones.png}"

View File

@ -84,6 +84,11 @@ namespace Microsoft.PowerToys.Settings.UI.OOBE.Views
ModuleName = "ColorPicker", ModuleName = "ColorPicker",
IsNew = false, IsNew = false,
}); });
Modules.Insert((int)PowerToysModules.CropAndLock, new OobePowerToysModule()
{
ModuleName = "CropAndLock",
IsNew = true,
});
Modules.Insert((int)PowerToysModules.FancyZones, new OobePowerToysModule() Modules.Insert((int)PowerToysModules.FancyZones, new OobePowerToysModule()
{ {
ModuleName = "FancyZones", ModuleName = "FancyZones",
@ -241,6 +246,7 @@ namespace Microsoft.PowerToys.Settings.UI.OOBE.Views
case "AlwaysOnTop": NavigationFrame.Navigate(typeof(OobeAlwaysOnTop)); break; case "AlwaysOnTop": NavigationFrame.Navigate(typeof(OobeAlwaysOnTop)); break;
case "Awake": NavigationFrame.Navigate(typeof(OobeAwake)); break; case "Awake": NavigationFrame.Navigate(typeof(OobeAwake)); break;
case "ColorPicker": NavigationFrame.Navigate(typeof(OobeColorPicker)); break; case "ColorPicker": NavigationFrame.Navigate(typeof(OobeColorPicker)); break;
case "CropAndLock": NavigationFrame.Navigate(typeof(OobeCropAndLock)); break;
case "FancyZones": NavigationFrame.Navigate(typeof(OobeFancyZones)); break; case "FancyZones": NavigationFrame.Navigate(typeof(OobeFancyZones)); break;
case "FileLocksmith": NavigationFrame.Navigate(typeof(OobeFileLocksmith)); break; case "FileLocksmith": NavigationFrame.Navigate(typeof(OobeFileLocksmith)); break;
case "Run": NavigationFrame.Navigate(typeof(OobeRun)); break; case "Run": NavigationFrame.Navigate(typeof(OobeRun)); break;

View File

@ -0,0 +1,73 @@
<Page
x:Class="Microsoft.PowerToys.Settings.UI.Views.CropAndLockPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:Microsoft.PowerToys.Settings.UI.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:labs="using:CommunityToolkit.Labs.WinUI"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ui="using:CommunityToolkit.WinUI.UI"
AutomationProperties.LandmarkType="Main"
mc:Ignorable="d">
<controls:SettingsPageControl
x:Uid="CropAndLock"
IsTabStop="False"
ModuleImageSource="ms-appx:///Assets/Settings/Modules/CropAndLock.png">
<controls:SettingsPageControl.ModuleContent>
<StackPanel Orientation="Vertical" ChildrenTransitions="{StaticResource SettingsCardsAnimations}">
<labs:SettingsCard
x:Uid="CropAndLock_EnableToggleControl_HeaderText"
HeaderIcon="{ui:BitmapIcon Source=/Assets/Settings/FluentIcons/FluentIconsCropAndLock.png}"
IsEnabled="{x:Bind Mode=OneWay, Path=ViewModel.IsEnabledGpoConfigured, Converter={StaticResource BoolNegationConverter}}">
<ToggleSwitch
x:Uid="ToggleSwitch"
IsOn="{x:Bind ViewModel.IsEnabled, Mode=TwoWay}" />
</labs:SettingsCard>
<InfoBar
x:Uid="GPO_IsSettingForced"
IsClosable="False"
IsOpen="{x:Bind Mode=OneWay, Path=ViewModel.IsEnabledGpoConfigured}"
IsTabStop="{x:Bind Mode=OneWay, Path=ViewModel.IsEnabledGpoConfigured}"
Severity="Informational" />
<controls:SettingsGroup
x:Uid="CropAndLock_Activation_GroupSettings"
IsEnabled="{x:Bind Mode=OneWay, Path=ViewModel.IsEnabled}">
<labs:SettingsCard
x:Uid="CropAndLock_ThumbnailActivation_Shortcut"
HeaderIcon="{ui:FontIcon FontFamily={StaticResource SymbolThemeFontFamily},
Glyph=&#xEDA7;}">
<controls:ShortcutControl
AllowDisable="True"
MinWidth="{StaticResource SettingActionControlMinWidth}"
HotkeySettings="{x:Bind Path=ViewModel.ThumbnailActivationShortcut, Mode=TwoWay}" />
</labs:SettingsCard>
<labs:SettingsCard
x:Uid="CropAndLock_ReparentActivation_Shortcut"
HeaderIcon="{ui:FontIcon FontFamily={StaticResource SymbolThemeFontFamily},
Glyph=&#xEDA7;}">
<controls:ShortcutControl
AllowDisable="True"
MinWidth="{StaticResource SettingActionControlMinWidth}"
HotkeySettings="{x:Bind Path=ViewModel.ReparentActivationShortcut, Mode=TwoWay}" />
</labs:SettingsCard>
</controls:SettingsGroup>
</StackPanel>
</controls:SettingsPageControl.ModuleContent>
<controls:SettingsPageControl.PrimaryLinks>
<controls:PageLink
x:Uid="LearnMore_CropAndLock"
Link="https://aka.ms/PowerToysOverview_CropAndLock" />
</controls:SettingsPageControl.PrimaryLinks>
<controls:SettingsPageControl.SecondaryLinks>
<controls:PageLink
Link="https://github.com/robmikh"
Text="Robert Mikhayelyan" />
<controls:PageLink
Link="https://github.com/kevinguo305"
Text="Kevin Guo" />
</controls:SettingsPageControl.SecondaryLinks>
</controls:SettingsPageControl>
</Page>

View File

@ -0,0 +1,29 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.PowerToys.Settings.UI.Helpers;
using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.PowerToys.Settings.UI.ViewModels;
using Microsoft.UI.Xaml.Controls;
namespace Microsoft.PowerToys.Settings.UI.Views
{
public sealed partial class CropAndLockPage : Page, IRefreshablePage
{
private CropAndLockViewModel ViewModel { get; set; }
public CropAndLockPage()
{
var settingsUtils = new SettingsUtils();
ViewModel = new CropAndLockViewModel(settingsUtils, SettingsRepository<GeneralSettings>.GetInstance(settingsUtils), SettingsRepository<CropAndLockSettings>.GetInstance(settingsUtils), ShellPage.SendDefaultIPCMessage);
DataContext = ViewModel;
InitializeComponent();
}
public void RefreshEnabledState()
{
ViewModel.RefreshEnabledState();
}
}
}

View File

@ -106,6 +106,11 @@
helpers:NavHelper.NavigateTo="views:ColorPickerPage" helpers:NavHelper.NavigateTo="views:ColorPickerPage"
Icon="{ui:BitmapIcon Source=/Assets/Settings/FluentIcons/FluentIconsColorPicker.png}" /> Icon="{ui:BitmapIcon Source=/Assets/Settings/FluentIcons/FluentIconsColorPicker.png}" />
<NavigationViewItem
x:Uid="Shell_CropAndLock"
helpers:NavHelper.NavigateTo="views:CropAndLockPage"
Icon="{ui:BitmapIcon Source=/Assets/Settings/FluentIcons/FluentIconsCropAndLock.png}" />
<NavigationViewItem <NavigationViewItem
x:Uid="Shell_FancyZones" x:Uid="Shell_FancyZones"
helpers:NavHelper.NavigateTo="views:FancyZonesPage" helpers:NavHelper.NavigateTo="views:FancyZonesPage"

View File

@ -2719,6 +2719,59 @@ Right-click to remove the key combination, thereby deactivating the shortcut.</v
<value>On</value> <value>On</value>
<comment>The state of a ToggleSwitch when it's on</comment> <comment>The state of a ToggleSwitch when it's on</comment>
</data> </data>
<data name="CropAndLock.ModuleDescription" xml:space="preserve">
<value>Crop And Lock allows you to crop a current application into a smaller window or just create a thumbnail. Focus the target window and press the shortcut to start cropping.</value>
<comment>"Crop And Lock" is the name of the utility</comment>
</data>
<data name="CropAndLock.ModuleTitle" xml:space="preserve">
<value>Crop And Lock </value>
<comment>"Crop And Lock" is the name of the utility</comment>
</data>
<data name="CropAndLock_Activation_GroupSettings.Header" xml:space="preserve">
<value>Activation</value>
</data>
<data name="CropAndLock_EnableToggleControl_HeaderText.Header" xml:space="preserve">
<value>Enable Crop And Lock</value>
<comment>"Crop And Lock" is the name of the utility</comment>
</data>
<data name="Shell_CropAndLock.Content" xml:space="preserve">
<value>Crop And Lock</value>
<comment>"Crop And Lock" is the name of the utility</comment>
</data>
<data name="LearnMore_CropAndLock.Text" xml:space="preserve">
<value>Learn more about Crop And Lock</value>
<comment>"Crop And Lock" is the name of the utility</comment>
</data>
<data name="CropAndLock_ReparentActivation_Shortcut.Header" xml:space="preserve">
<value>Reparent shortcut</value>
</data>
<data name="CropAndLock_ReparentActivation_Shortcut.Description" xml:space="preserve">
<value>Shortcut to crop an application's window into a cropped window. This is experimental and can cause issues with some applications, since the cropped window will contain the original application window.</value>
</data>
<data name="CropAndLock_ThumbnailActivation_Shortcut.Header" xml:space="preserve">
<value>Thumbnail shortcut</value>
</data>
<data name="CropAndLock_ThumbnailActivation_Shortcut.Description" xml:space="preserve">
<value>Shortcut to crop and create a thumbnail of another window. The application isn't controllable through the thumbnail but it'll have less compatibility issues. </value>
</data>
<data name="CropAndLock.SecondaryLinksHeader" xml:space="preserve">
<value>Attribution</value>
<comment>giving credit to the projects this utility was based on</comment>
</data>
<data name="Oobe_CropAndLock.Title" xml:space="preserve">
<value>Crop And Lock</value>
<comment>"Crop And Lock" is the name of the utility</comment>
</data>
<data name="Oobe_CropAndLock.Description" xml:space="preserve">
<value>Crop And Lock allows you to crop a current application into a smaller window or just create a thumbnail. Focus the target window and press the shortcut to start cropping.</value>
<comment>"Crop And Lock" is the name of the utility</comment>
</data>
<data name="Oobe_CropAndLock_HowToUse_Thumbnail.Text" xml:space="preserve">
<value>to crop and create a thumbnail of another window. The application isn't controllable through the thumbnail but it'll have less compatibility issues.</value>
</data>
<data name="Oobe_CropAndLock_HowToUse_Reparent.Text" xml:space="preserve">
<value>to crop an application's window into a cropped window. This is experimental and can cause issues with some applications, since the cropped window will contain the original application window.</value>
</data>
<data name="AlwaysOnTop.ModuleDescription" xml:space="preserve"> <data name="AlwaysOnTop.ModuleDescription" xml:space="preserve">
<value>Always On Top is a quick and easy way to pin windows on top.</value> <value>Always On Top is a quick and easy way to pin windows on top.</value>
<comment>"Always On Top" is the name of the utility</comment> <comment>"Always On Top" is the name of the utility</comment>

View File

@ -0,0 +1,187 @@
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text.Json;
using global::PowerToys.GPOWrapper;
using Microsoft.PowerToys.Settings.UI.Library;
using Microsoft.PowerToys.Settings.UI.Library.Helpers;
using Microsoft.PowerToys.Settings.UI.Library.Interfaces;
using Microsoft.PowerToys.Settings.UI.Library.Utilities;
namespace Microsoft.PowerToys.Settings.UI.ViewModels
{
public class CropAndLockViewModel : Observable
{
private ISettingsUtils SettingsUtils { get; set; }
private GeneralSettings GeneralSettingsConfig { get; set; }
private CropAndLockSettings Settings { get; set; }
private Func<string, int> SendConfigMSG { get; }
public CropAndLockViewModel(ISettingsUtils settingsUtils, ISettingsRepository<GeneralSettings> settingsRepository, ISettingsRepository<CropAndLockSettings> moduleSettingsRepository, Func<string, int> ipcMSGCallBackFunc)
{
if (settingsUtils == null)
{
throw new ArgumentNullException(nameof(settingsUtils));
}
SettingsUtils = settingsUtils;
// To obtain the general settings configurations of PowerToys Settings.
if (settingsRepository == null)
{
throw new ArgumentNullException(nameof(settingsRepository));
}
GeneralSettingsConfig = settingsRepository.SettingsConfig;
InitializeEnabledValue();
// To obtain the settings configurations of CropAndLock.
if (moduleSettingsRepository == null)
{
throw new ArgumentNullException(nameof(moduleSettingsRepository));
}
Settings = moduleSettingsRepository.SettingsConfig;
_reparentHotkey = Settings.Properties.ReparentHotkey.Value;
_thumbnailHotkey = Settings.Properties.ThumbnailHotkey.Value;
// set the callback functions value to hangle outgoing IPC message.
SendConfigMSG = ipcMSGCallBackFunc;
}
private void InitializeEnabledValue()
{
_enabledGpoRuleConfiguration = GPOWrapper.GetConfiguredCropAndLockEnabledValue();
if (_enabledGpoRuleConfiguration == GpoRuleConfigured.Disabled || _enabledGpoRuleConfiguration == GpoRuleConfigured.Enabled)
{
// Get the enabled state from GPO.
_enabledStateIsGPOConfigured = true;
_isEnabled = _enabledGpoRuleConfiguration == GpoRuleConfigured.Enabled;
}
else
{
_isEnabled = GeneralSettingsConfig.Enabled.CropAndLock;
}
}
public bool IsEnabled
{
get => _isEnabled;
set
{
if (_enabledStateIsGPOConfigured)
{
// If it's GPO configured, shouldn't be able to change this state.
return;
}
if (value != _isEnabled)
{
_isEnabled = value;
// Set the status in the general settings configuration
GeneralSettingsConfig.Enabled.CropAndLock = value;
OutGoingGeneralSettings snd = new OutGoingGeneralSettings(GeneralSettingsConfig);
SendConfigMSG(snd.ToString());
OnPropertyChanged(nameof(IsEnabled));
}
}
}
public bool IsEnabledGpoConfigured
{
get => _enabledStateIsGPOConfigured;
}
public HotkeySettings ReparentActivationShortcut
{
get => _reparentHotkey;
set
{
if (value != _reparentHotkey)
{
if (value == null)
{
_reparentHotkey = CropAndLockProperties.DefaultReparentHotkeyValue;
}
else
{
_reparentHotkey = value;
}
Settings.Properties.ReparentHotkey.Value = _reparentHotkey;
NotifyPropertyChanged();
// Using InvariantCulture as this is an IPC message
SendConfigMSG(
string.Format(
CultureInfo.InvariantCulture,
"{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
CropAndLockSettings.ModuleName,
JsonSerializer.Serialize(Settings)));
}
}
}
public HotkeySettings ThumbnailActivationShortcut
{
get => _thumbnailHotkey;
set
{
if (value != _thumbnailHotkey)
{
if (value == null)
{
_thumbnailHotkey = CropAndLockProperties.DefaultThumbnailHotkeyValue;
}
else
{
_thumbnailHotkey = value;
}
Settings.Properties.ThumbnailHotkey.Value = _thumbnailHotkey;
NotifyPropertyChanged();
// Using InvariantCulture as this is an IPC message
SendConfigMSG(
string.Format(
CultureInfo.InvariantCulture,
"{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
CropAndLockSettings.ModuleName,
JsonSerializer.Serialize(Settings)));
}
}
}
public void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
{
OnPropertyChanged(propertyName);
SettingsUtils.SaveSettings(Settings.ToJsonString(), CropAndLockSettings.ModuleName);
}
public void RefreshEnabledState()
{
InitializeEnabledValue();
OnPropertyChanged(nameof(IsEnabled));
}
private GpoRuleConfigured _enabledGpoRuleConfiguration;
private bool _enabledStateIsGPOConfigured;
private bool _isEnabled;
private HotkeySettings _reparentHotkey;
private HotkeySettings _thumbnailHotkey;
}
}

View File

@ -47,6 +47,11 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
FlyoutMenuItems.Add(new FlyoutMenuItem() { Label = resourceLoader.GetString("ColorPicker/ModuleTitle"), IsEnabled = generalSettingsConfig.Enabled.ColorPicker, Tag = "ColorPicker", Icon = "ms-appx:///Assets/Settings/FluentIcons/FluentIconsColorPicker.png", EnabledChangedCallback = EnabledChangedOnUI }); FlyoutMenuItems.Add(new FlyoutMenuItem() { Label = resourceLoader.GetString("ColorPicker/ModuleTitle"), IsEnabled = generalSettingsConfig.Enabled.ColorPicker, Tag = "ColorPicker", Icon = "ms-appx:///Assets/Settings/FluentIcons/FluentIconsColorPicker.png", EnabledChangedCallback = EnabledChangedOnUI });
} }
if ((gpo = GPOWrapper.GetConfiguredCropAndLockEnabledValue()) != GpoRuleConfigured.Disabled && gpo != GpoRuleConfigured.Enabled)
{
FlyoutMenuItems.Add(new FlyoutMenuItem() { Label = resourceLoader.GetString("CropAndLock/ModuleTitle"), IsEnabled = generalSettingsConfig.Enabled.CropAndLock, Tag = "CropAndLock", Icon = "ms-appx:///Assets/Settings/FluentIcons/FluentIconsCropAndLock.png", EnabledChangedCallback = EnabledChangedOnUI });
}
if ((gpo = GPOWrapper.GetConfiguredFancyZonesEnabledValue()) != GpoRuleConfigured.Disabled && gpo != GpoRuleConfigured.Enabled) if ((gpo = GPOWrapper.GetConfiguredFancyZonesEnabledValue()) != GpoRuleConfigured.Disabled && gpo != GpoRuleConfigured.Enabled)
{ {
FlyoutMenuItems.Add(new FlyoutMenuItem() { Label = resourceLoader.GetString("FancyZones/ModuleTitle"), IsEnabled = generalSettingsConfig.Enabled.FancyZones, Tag = "FancyZones", Icon = "ms-appx:///Assets/Settings/FluentIcons/FluentIconsFancyZones.png", EnabledChangedCallback = EnabledChangedOnUI }); FlyoutMenuItems.Add(new FlyoutMenuItem() { Label = resourceLoader.GetString("FancyZones/ModuleTitle"), IsEnabled = generalSettingsConfig.Enabled.FancyZones, Tag = "FancyZones", Icon = "ms-appx:///Assets/Settings/FluentIcons/FluentIconsFancyZones.png", EnabledChangedCallback = EnabledChangedOnUI });
@ -165,6 +170,7 @@ namespace Microsoft.PowerToys.Settings.UI.ViewModels
case "AlwaysOnTop": item.IsEnabled = generalSettingsConfig.Enabled.AlwaysOnTop; break; case "AlwaysOnTop": item.IsEnabled = generalSettingsConfig.Enabled.AlwaysOnTop; break;
case "Awake": item.IsEnabled = generalSettingsConfig.Enabled.Awake; break; case "Awake": item.IsEnabled = generalSettingsConfig.Enabled.Awake; break;
case "ColorPicker": item.IsEnabled = generalSettingsConfig.Enabled.ColorPicker; break; case "ColorPicker": item.IsEnabled = generalSettingsConfig.Enabled.ColorPicker; break;
case "CropAndLock": item.IsEnabled = generalSettingsConfig.Enabled.CropAndLock; break;
case "FancyZones": item.IsEnabled = generalSettingsConfig.Enabled.FancyZones; break; case "FancyZones": item.IsEnabled = generalSettingsConfig.Enabled.FancyZones; break;
case "FileLocksmith": item.IsEnabled = generalSettingsConfig.Enabled.FileLocksmith; break; case "FileLocksmith": item.IsEnabled = generalSettingsConfig.Enabled.FileLocksmith; break;
case "FindMyMouse": item.IsEnabled = generalSettingsConfig.Enabled.FindMyMouse; break; case "FindMyMouse": item.IsEnabled = generalSettingsConfig.Enabled.FindMyMouse; break;

View File

@ -38,4 +38,5 @@ std::vector<std::wstring> processes =
L"PowerToys.MouseWithoutBordersHelper.exe", L"PowerToys.MouseWithoutBordersHelper.exe",
L"PowerToys.MouseWithoutBordersService.exe", L"PowerToys.MouseWithoutBordersService.exe",
L"PowerToys.Peek.UI.exe", L"PowerToys.Peek.UI.exe",
L"PowerToys.CropAndLock.exe",
}; };

View File

@ -31,6 +31,7 @@ void ReportGPOValues(const std::filesystem::path& tmpDir)
report << "getConfiguredAlwaysOnTopEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredAlwaysOnTopEnabledValue()) << std::endl; report << "getConfiguredAlwaysOnTopEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredAlwaysOnTopEnabledValue()) << std::endl;
report << "getConfiguredAwakeEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredAwakeEnabledValue()) << std::endl; report << "getConfiguredAwakeEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredAwakeEnabledValue()) << std::endl;
report << "getConfiguredColorPickerEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredColorPickerEnabledValue()) << std::endl; report << "getConfiguredColorPickerEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredColorPickerEnabledValue()) << std::endl;
report << "getConfiguredCropAndLockEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredCropAndLockEnabledValue()) << std::endl;
report << "getConfiguredFancyZonesEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredFancyZonesEnabledValue()) << std::endl; report << "getConfiguredFancyZonesEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredFancyZonesEnabledValue()) << std::endl;
report << "getConfiguredFileLocksmithEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredFileLocksmithEnabledValue()) << std::endl; report << "getConfiguredFileLocksmithEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredFileLocksmithEnabledValue()) << std::endl;
report << "getConfiguredSvgPreviewEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredSvgPreviewEnabledValue()) << std::endl; report << "getConfiguredSvgPreviewEnabledValue: " << gpo_rule_configured_to_string(powertoys_gpo::getConfiguredSvgPreviewEnabledValue()) << std::endl;