[DevDocs] More content and restructure (#40165)
Some checks failed
Spell checking / Check Spelling (push) Has been cancelled
Spell checking / Report (Push) (push) Has been cancelled
Spell checking / Report (PR) (push) Has been cancelled
Spell checking / Update PR (push) Has been cancelled

## Summary of the Pull Request
Accumulated information from internal transition about the modules
development, and reworked it to be added in dev docs. Also the dev docs
intself was restructured to be more organized. New pages was
verified by transition team.

## PR Checklist
- [x] **Dev docs:** Added/updated

---------

Co-authored-by: Zhaopeng Wang (from Dev Box) <zhaopengwang@microsoft.com>
Co-authored-by: Hao Liu <liuhao3418@gmail.com>
Co-authored-by: Peiyao Zhao <105847726+zhaopy536@users.noreply.github.com>
Co-authored-by: Mengyuan <162882040+chenmy77@users.noreply.github.com>
Co-authored-by: zhaopeng wang <33367956+wang563681252@users.noreply.github.com>
Co-authored-by: Jaylyn Barbee <51131738+Jaylyn-Barbee@users.noreply.github.com>
This commit is contained in:
Gleb Khmyznikov
2025-07-01 14:27:34 +02:00
committed by GitHub
parent 9c2e83d6eb
commit 725535b760
102 changed files with 5361 additions and 325 deletions

View File

@@ -0,0 +1,31 @@
# Advanced Paste
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/advanced-paste)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Advanced%20Paste%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Advanced%20Paste%22%20label%3AIssue-Bug)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen++label%3A%22Product-Advanced+Paste%22)
## Overview
Advanced Paste is a PowerToys module that provides enhanced clipboard pasting with formatting options and additional functionality.
## Implementation Details
[Source code](/src/modules/AdvancedPaste)
TODO: Add implementation details
## Debugging
TODO: Add debugging information
## Settings
TODO: Add settings documentation
## Future Improvements
TODO: Add potential future improvements

View File

@@ -0,0 +1,98 @@
# Always on Top
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/always-on-top)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Always%20On%20Top%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20%20label%3A%22Product-Always%20On%20Top%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen++label%3A%22Product-Always+On+Top%22+)
## Overview
The Always on Top module allows users to pin windows on top of others, ensuring they remain visible even when switching between applications. The module provides visual indicators (customizable borders) to identify which windows are pinned.
## Features
- Pin any window to stay on top of other windows
- Customizable border color, opacity, and thickness around pinned windows
- User-defined keyboard shortcut for toggling window pinning
- Visual indicators to identify pinned windows
## Architecture
### Main Components
- **Hotkey Listener**: Detects the user-defined hotkey to toggle the Always on Top state
- **AlwaysOnTop**: Manages the state of windows, ensuring the selected window stays on top
- **Settings**: Stores user preferences and configurations
- **WindowHook**: Hooks all window events
### Data Flow
1. The Hotkey Listener detects the hotkey press and notifies the AlwaysOnTop
2. The AlwaysOnTop updates the window state and interacts with the operating system to keep the window on top
3. User preferences are saved and loaded from the Settings
## Code Structure
### Key Files
- **AlwaysOnTop.cpp**: Contains the core logic for the module, including initialization and event handling
- **Settings.cpp**: Defines the settings structure and provides methods to load and save settings
- **main.cpp**: Starts thread and initializes AlwaysOnTop
### Initialization
The module is initialized in the AlwaysOnTop class. During initialization, the following steps are performed:
1. **LoadSettings**: The module loads user settings from a configuration file
2. **RegisterHotkey**: The HotkeyManager registers the keyboard shortcut for pinning/unpinning windows
3. **SubscribeToEvents**: Event handlers are attached to respond to user actions, such as pressing the hotkey
### Pinning and Unpinning Windows
The AlwaysOnTop class handles the pinning and unpinning of windows. Key methods include:
- **PinTopmostWindow**: Pins the specified window on top of others and applies visual indicators
- **UnpinTopmostWindowss**: Removes the pinning status and visual indicators from the specified window
- **AssignBorder**: Applies a colored border around the pinned window based on user settings
### Settings Management
The Settings class manages the module's settings. Key methods include:
- **LoadSettings**: Loads settings from a configuration file
- **NotifyObservers**: Distributes the data for the settings
- **GetDefaultSettings**: Returns the default settings for the module
## User Interface
The module provides a user interface for configuring settings in the PowerToys Settings UI. This interface is implemented using XAML and includes options for customizing the:
- Border color
- Border opacity
- Border thickness
- Keyboard shortcut
## Development Environment Setup
### Prerequisites
- Visual Studio 2019 or later
- Windows 10 SDK
- PowerToys repository cloned from GitHub
### Building and Testing
1. Clone the repository: `git clone https://github.com/microsoft/PowerToys.git`
2. Open PowerToys.sln in Visual Studio
3. Select the Release configuration and build the solution
4. Run PowerToys.exe from the output directory to test the module
### Debug
1. build the entire project
2. launch the built Powertoys
3. select AlwaysOnTop as the startup project in VS
4. In the debug button, choose "Attach to process". ![image](https://github.com/user-attachments/assets/a7624ec2-63f1-4720-9540-a916b0ada282)
5. Attach to AlwaysOnTop.![image](https://github.com/user-attachments/assets/815c0f89-8fd1-48d6-b7fd-0e4a92e222d0)

View File

@@ -0,0 +1,44 @@
# Awake
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/awake)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AProduct-Awake)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20%20label%3AProduct-Awake)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen++label%3A%22Product-Awake%22+)
## Overview
Awake is a PowerToys utility designed to keep your computer awake without permanently modifying system power settings. It prevents the computer from sleeping and can keep the monitor on, providing a convenient alternative to changing system power configurations.
## Key Features
- Temporarily override system sleep settings
- Keep monitor on (prevent display from turning off)
- Set time intervals for keeping the system awake
- One-time setup with no need to revert power settings afterward
## Advantages Over System Power Settings
- **Convenience**: Easy UI for quick toggling of sleep prevention
- **Flexibility**: Support for different time intervals (indefinitely, for specific duration)
- **Non-persistent**: Changes are temporary and don't require manual reversion
- **Quick Access**: Available directly from the system tray
## Architecture
### Components
- **System Tray UI**: Provides user interface for controlling Awake settings
- **Backend Threads**: Manages the power state prevention functionality
- **Command Line Interface**: Supports various commands for controlling Awake functionality programmatically
## Technical Implementation
Awake works by preventing system sleep through Windows power management APIs. The module runs as a background process that interfaces with the Windows power management system to keep the device awake according to user preferences.
## User Experience
Users can access Awake through the PowerToys system tray icon. From there, they can:
1. Toggle Awake on/off
2. Set a specific duration for keeping the system awake
3. Choose whether to keep the display on or allow it to turn off
4. Access additional configuration options
## Command Line Support
Awake includes command-line functionality for power users and automation scenarios, allowing programmatic control of the utility's features.

View File

@@ -0,0 +1,49 @@
# Color Picker
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/color-picker)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Color%20Picker%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-Color%20Picker%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen++label%3A%22Product-Color+Picker%22)
## Overview
Color Picker is a system-wide color picking utility for Windows that allows users to pick colors from any screen and copy them to the clipboard in a configurable format.
## Implementation Details
### Color Capturing Mechanism
The Color Picker works by following these steps to capture the color at the current mouse position:
1. Obtain the position of the mouse
2. Create a 1x1 size rectangle at that position
3. Create a Bitmap class and use it to initiate a Graphics object
4. Create an image associated with the Graphics object by leveraging the CopyFromScreen function, which captures the pixel information from the specified location
### Core Color Picking Function
The following code snippet demonstrates the core functionality of how a color is picked from the screen:
```csharp
private static Color GetPixelColor(System.Windows.Point mousePosition)
{
var rect = new Rectangle((int)mousePosition.X, (int)mousePosition.Y, 1, 1);
using (var bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb))
{
var g = Graphics.FromImage(bmp);
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
return bmp.GetPixel(0, 0);
}
}
```
## Features
- Pick colors from any pixel on the screen
- View color information in various formats (RGB, HEX, HSL, etc.)
- Copy color values to clipboard in configurable formats
- Color history for quick access to previously selected colors
- Keyboard shortcuts for quick activation and operation
## User Experience
When activated, Color Picker displays a magnified view of the area around the cursor to allow for precise color selection. Once a color is selected, it can be copied to the clipboard in the user's preferred format for use in design tools, development environments, or other applications.

View File

@@ -0,0 +1,43 @@
# Command Not Found
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/cmd-not-found)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AProduct-CommandNotFound)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3AProduct-CommandNotFound)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3AProduct-CommandNotFound)
## Overview
Command Not Found is a PowerToys module that suggests package installations when you attempt to run a command that isn't available on your system. It integrates with the Windows command line to provide helpful suggestions for installing missing commands through package managers.
## How it Works
When you attempt to execute a command in the terminal that isn't found, the Command Not Found module intercepts this error and checks if the command is available in known package repositories. If a match is found, it suggests the appropriate installation command.
## Installation
The Command Not Found module requires the Microsoft.WinGet.CommandNotFound PowerShell module to function properly. When enabling the module through PowerToys, it automatically attempts to install this dependency.
The installation is handled by the following script:
```powershell
# Located in PowerToys\src\settings-ui\Settings.UI\Assets\Settings\Scripts\EnableModule.ps1
Install-Module -Name Microsoft.WinGet.CommandNotFound -Force
```
## Usage
1. Enable the Command Not Found module in PowerToys settings.
2. Open a terminal and try to run a command that isn't installed on your system.
3. If the command is available in a package, you'll see a suggestion for how to install it.
Example:
```
C:\> kubectl
'kubectl' is not recognized as an internal or external command, operable program, or batch file.
Command 'kubectl' not found, but can be installed with:
winget install -e --id Kubernetes.kubectl
```
## Technical Details
The Command Not Found module leverages the Microsoft.WinGet.CommandNotFound PowerShell module, which is maintained in a separate repository: https://github.com/microsoft/winget-command-not-found
The module works by registering a command-not-found handler that intercepts command execution failures and provides installation suggestions based on available packages in the WinGet repository.

View File

@@ -0,0 +1,45 @@
# Crop and Lock
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/crop-and-lock)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AProduct-CropAndLock)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3AProduct-CropAndLock)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3AProduct-CropAndLock)
## Overview
The Crop and Lock module in PowerToys allows users to crop a current application into a smaller window or create a thumbnail. This utility enhances productivity by enabling users to focus on specific parts of an application window.
## Features
### Thumbnail Mode
Creates a window showing the selected area of the original window. Changes in the original window are reflected in the thumbnail.
### Reparent Mode
Creates a window that replaces the original window, showing only the selected area. The application is controlled through the cropped window.
## Code Structure
### Project Layout
The Crop and Lock module is part of the PowerToys solution. All the logic-related settings are in the main.cpp. The main implementations are in ThumbnailCropAndLockWindow and ReparentCropAndLockWindow. ChildWindow and OverlayWindow distinguish the two different modes of windows implementations.
### Key Files
- **ThumbnailCropAndLockWindow.cpp**: Defines the UI for the thumbnail mode.
- **OverlayWindow.cpp**: Thumbnail module type's window concrete implementation.
- **ReparentCropAndLockWindow.cpp**: Defines the UI for the reparent mode.
- **ChildWindow.cpp**: Reparent module type's window concrete implementation.
## Known Issues
- Cropping maximized or full-screen windows in "Reparent" mode might not work properly.
- Some UWP apps may not respond well to being cropped in "Reparent" mode.
- Applications with sub-windows or tabs can have compatibility issues in "Reparent" mode.
## Debug
1. build the entire project
2. launch the built Powertoys
3. select CropAndLock as the startup project in VS
4. In the debug button, choose "Attach to process". ![image](https://github.com/user-attachments/assets/a7624ec2-63f1-4720-9540-a916b0ada282)
5. Attach to CropAndLock.![image](https://github.com/user-attachments/assets/08aa0465-596c-4494-9daa-e96b234f9997)

View File

@@ -0,0 +1,71 @@
# Environment Variables
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/environment-variables)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Environment%20Variables%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-Environment%20Variables%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-Environment+Variables%22)
[Checklist](https://github.com/microsoft/PowerToys/blob/releaseChecklist/doc/releases/tests-checklist-template.md?plain=1#L744)
## Overview
Environment Variables is a PowerToys module that provides an easy and convenient way to manage Windows environment variables. It offers a modern user interface for viewing, editing, and managing both user and system environment variables.
## Features
- View and edit user and system environment variables in a unified interface
- Create profiles to group and manage sets of variables together
- Profile-based variable management with on/off toggles
- Automatic backup of existing variables when overridden by a profile
- Restoration of original values when profiles are disabled
## How It Works
### Profiles
Profiles are collections of environment variables that can be enabled or disabled together. When a profile is enabled:
1. Variables in the profile override existing User variables with the same name
2. Original values are automatically backed up for restoration when the profile is disabled
3. Only one profile can be active at a time
### Variable Precedence
The module follows this precedence order for environment variables:
1. Active profile variables (highest precedence)
2. User variables
3. System variables (lowest precedence)
## Architecture
The Environment Variables module is structured into three main components:
### Project Structure
```
EnvironmentVariables/ # Contains assets, main windows, and telemetry
EnvironmentVariablesModuleInterface # Interface definitions and package configurations
EnvironmentVariableUILib # Abstracted UI methods and implementations
```
### Key Components
- **Main Window Framework**: Builds the modern Windows desktop UI, handles Windows messages, resource loading, and window closing operations
- **Project Configuration**: Defines settings and configurations for the module
- **UI Implementation**: Contains the user interface components and the backend logic
## Implementation Details
### Key Functions
- **OpenEnvironmentKeyIfExists**: Accesses environment information through registry keys
- **SetEnvironmentVariableFromRegistryWithoutNotify**: Sets variables directly to registry instead of using Environment API, avoiding the 1-second timeout for settings change notifications
- **GetVariables**: Reads variables directly from registry instead of using Environment API to prevent automatic variable expansion
### Technical Notes
- The module reads and writes variables directly to the registry instead of using the Environment API
- This direct registry access approach is used because the Environment API automatically expands variables and has a timeout for notifications
- When a profile variable has the same name as an existing User variable, a backup is created with a naming pattern: `VARIABLE_NAME_powertoys_PROFILE_NAME`

View File

@@ -0,0 +1,131 @@
# FancyZones Debugging Tools
## Overview
FancyZones has several specialized debugging tools to help diagnose issues with window management, zone detection, and rendering. These tools are designed to isolate and test specific components of the FancyZones functionality.
## Tools Summary
| Tool | Purpose | Key Functionality |
|------|---------|-------------------|
| FancyZones_HitTest | Tests zone hit detection | Shows which zone is under cursor with detailed metrics |
| FancyZones_DrawLayoutTest | Tests layout drawing | Renders zone layouts to debug display issues |
| FancyZones_zonable_tester | Tests window zonability | Determines if windows can be placed in zones |
| StylesReportTool | Analyzes window properties | Generates window style reports for debugging |
## FancyZones_HitTest
![Image of the FancyZones hit test tool](/doc/images/tools/fancyzones-hit-test.png)
### Purpose
Tests the FancyZones layout selection logic by displaying a window with zones and highlighting the zone under the mouse cursor.
### Functionality
- Displays a window with 5 sample zones
- Highlights the zone under the mouse cursor
- Shows metrics used for zone detection in a sidebar
- Helps diagnose issues with zone positioning and hit testing
### Usage
- Run the tool and move your mouse over the zones
- The currently detected zone will be highlighted
- The sidebar displays metrics used for determining the active zone
- Useful for debugging hit detection, positioning, and DPI issues
## FancyZones_DrawLayoutTest
### Purpose
Debug issues related to the drawing of zone layouts on screen.
### Functionality
- Simulates zone layouts (currently only column layout supported)
- Tests rendering of zones with different configurations
- Helps diagnose display issues across monitor configurations
### Usage
- Run the tool
- Press **W** key to toggle zone appearance on the primary screen
- Press **Q** key to exit the application
- The number of zones can be modified in the source code
### Technical Notes
The application is DPI unaware, meaning it doesn't scale for DPI changes and always assumes a scale factor of 100% (96 DPI). Scaling is automatically performed by the system.
## FancyZones_zonable_tester
![Image of the FancyZones zonable tester](/doc/images/tools/fancyzones-zonable-tester.png)
### Purpose
Tests if the window under the mouse cursor is "zonable" (can be placed in a FancyZones zone).
### Functionality
- Analyzes the window under the cursor
- Provides detailed window information:
* HWND (window handle)
* Process ID
* HWND of foreground window
* Window style flags
* Extended style flags
* Window class
* Process path
### Usage
- Run the command-line application
- Hover the mouse over a window to test
- Review the console output for detailed window information
- Check if the window is considered zonable by FancyZones
### Limitations
Note that this tool may not be fully up-to-date with the latest zonable logic in the main FancyZones codebase.
## StylesReportTool
### Purpose
Generates detailed reports about window styles that affect zonability.
### Functionality
- Creates comprehensive window style reports
- Focuses on style flags that determine if windows can be placed in zones
- Outputs report to "WindowStyles.txt" on the desktop
### Usage
- Run the tool
- Focus the window you want to analyze
- Press **Ctrl+Alt+S** to generate a report
- Review WindowStyles.txt to understand why a window might not be zonable
## Debugging Workflow
For most effective debugging of FancyZones issues:
1. Use **StylesReportTool** to analyze window properties of problematic windows
2. Use **FancyZones_zonable_tester** to check if specific windows can be zoned
3. Use **FancyZones_draw** for layout rendering issues on different monitors
4. Use **FancyZones_HitTest** for diagnosing zone detection problems
## Testing Considerations
When testing FancyZones with these tools, consider:
- Testing on different Windows versions
- Testing with multiple monitors with different:
* Resolutions
* Scaling settings
* Physical arrangements
- Testing with various window types:
* Standard applications
* Legacy applications
* UWP/WinUI applications
* Administrative windows
* Special windows (like Task Manager)
- Testing various layouts:
* Grid layouts
* Custom layouts
* Overlapping zones
## Initial Setup Issues
If encountering JSON token errors on first run:
1. Launch FancyZones Editor through PowerToys Settings UI
2. This initializes required configuration files
3. Direct project execution won't initialize configs properly

View File

@@ -1,13 +1,246 @@
# FancyZones UI tests
# FancyZones
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/fancyzones)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AProduct-FancyZones)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3AProduct-FancyZones)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3AProduct-FancyZones)
## Overview
FancyZones is a window manager utility that allows users to create custom layouts for organizing windows on their screen.
## Architecture Overview
FancyZones consists of several interconnected components:
### Directory Structure
- **src**: Contains the source code for FancyZones.
- **Editor**: Code for the zone editor.
- **Runner**: Code for the zone management and window snapping.
- **Settings**: Code for managing user settings.
- **tests**: Contains unit and integration tests for FancyZones and UI test code.
### Project Structure
FancyZones is divided into several projects:
- **FancyZones**: Used for thread starting and module initialization.
- **FancyZonesLib**: Contains the main backend logic, called by FancyZones (via COM).
- **FancyZonesData** folder: Contains classes and utilities for managing FancyZones data.
- **FancyZonesEditor**: Main UI implementation for creating and editing layouts.
- **FancyZonesEditorCommon**: Stores editor's data and provides shared functionality.
- **FancyZonesModuleInterface**: Interface layer between FancyZones and the PowerToys Runner.
### Interface Layer: FancyZonesModuleInterface
- Exposes interface between FancyZones and the Runner
- Handles communication and configuration exchange
- Contains minimal code, most logic implemented in other modules
### UI Layer: FancyZonesEditor and FancyZonesEditorCommon
- **FancyZonesEditor**: Main UI implementation with MainWindow.xaml as entry point
- **FancyZonesEditorCommon**: Provides data structures and I/O helpers for the Editor
- Acts as a visual config editor for layout configuration
![Editor Code Map](../images/fancyzones/editor_map.png)
![Editor Common Code Map](../images/fancyzones/editor_common_map.png)
### Backend Implementation: FancyZones and FancyZonesLib
- **FancyZonesLib**: Core logic implementation
- All drag-and-drop behavior
- Layout UI during dragging (generated in C++ via WorkArea.cpp, NewZonesOverlayWindow function)
- Core data structures
- **FancyZones**: Wrapper around FancyZonesLib
### Data Flow
- User interactions with the Editor are saved in the Settings
- The Runner reads the Settings to apply the zones and manage window positions
- Editor sends update events, which trigger FancyZones to refresh memory data
## Key Files
### FancyZones and FancyZonesLib Projects
- **FancyZonesApp.h/cpp**:
- **FancyZonesApp Class**: Initializes and manages the FancyZones application.
- **Constructor**: Initializes DPI awareness, sets up event hooks, creates the FancyZones instance.
- **Destructor**: Cleans up resources, destroys the FancyZones instance, unhooks event hooks.
- **Run Method**: Starts the FancyZones application.
- **InitHooks Method**: Sets up Windows event hooks to monitor system events.
- **DisableModule Method**: Posts a quit message to the main thread.
- **HandleWinHookEvent/HandleKeyboardHookEvent Methods**: Handle Windows event hooks.
- **Data Management Files**:
- **AppliedLayouts.h/cpp**: Manages applied layouts for different monitors and virtual desktops.
- **AppZoneHistory.h/cpp**: Tracks history of app zones.
- **CustomLayouts.h/cpp**: Handles user-created layouts.
- **DefaultLayouts.h/cpp**: Manages default layouts for different monitor configurations.
- **LayoutHotkeys.h/cpp**: Manages hotkeys for switching layouts.
- **LayoutTemplates.h/cpp**: Handles layout templates.
- **Core Functionality**:
- **FancyZonesDataTypes.h**: Defines data types used throughout FancyZones.
- **FancyZonesWindowProcessing.h/cpp**: Processes window events like moving and resizing.
- **FancyZonesWindowProperties.h/cpp**: Manages window properties like assigned zones.
- **JsonHelpers.h/cpp**: Utilities for JSON serialization/deserialization.
- **Layout.h/cpp**: Defines the Layout class for zone layout management.
- **LayoutConfigurator.h/cpp**: Configures different layout types (grid, rows, columns).
- **Settings.h/cpp**: Manages FancyZones module settings.
### FancyZonesEditor and FancyZonesEditorCommon Projects
- **UI Components**:
- **MainWindow.xaml/cs**: Main window of the FancyZones Editor.
- **EditorOverlay.xaml/cs**: Overlay window for editing zones.
- **EditorSettings.xaml/cs**: Settings window for the FancyZones Editor.
- **LayoutPreview.xaml/cs**: Provides layout preview.
- **ZoneSettings.xaml/cs**: Manages individual zone settings.
- **Data Components**:
- **EditorParameters.cs**: Parameters used by the FancyZones Editor.
- **LayoutData.cs**: Manages data for individual layouts.
- **LayoutHotkeys.cs**: Manages hotkeys for switching layouts.
- **LayoutTemplates.cs**: Manages layout templates.
- **Zone.cs**: Represents an individual zone.
- **ZoneSet.cs**: Manages sets of zones within a layout.
## Configuration Management
### Configuration Files Location
- Path: `C:\Users\[username]\AppData\Local\Microsoft\PowerToys\FancyZones`
- Files:
- EditorParameters
- AppliedLayouts
- CustomLayouts
- DefaultLayouts
- LayoutHotkeys
- LayoutTemplates
- AppZoneHistory
### Configuration Handling
- No central configuration handler
- Editor: Read/write handlers in FancyZonesEditorCommon project
- FancyZones: Read/write handlers in FancyZonesLib project
- Data synchronization: Editor sends update events, FancyZones refreshes memory data
## Window Management
### Monitor Detection and DPI Scaling
- Monitor detection handled in `FancyZones::MoveSizeUpdate` function
- DPI scaling: FancyZones retrieves window position without needing mouse DPI scaling info
- Window scaling uses system interface via `WindowMouseSnap::MoveSizeEnd()` function
### Zone Tracking
- Window-to-zone tracking implemented in `FancyZones::MoveSizeUpdate` function
- Maintains history of which windows belong to which zones
## Development History
- FancyZones was originally developed as a proof of concept
- Many configuration options were added based on community feedback after initial development
- Some options were added to address specific issues:
- Options for child windows or pop-up windows
- Some options were removed later
- Community feedback led to more interactions being implemented
## Admin Mode Considerations
- FancyZones can't move admin windows unless running as admin
- By default, all utilities run as admin if PowerToys is running as admin
## Development Environment Setup
### Prerequisites
- Visual Studio 2022: Required for building and debugging
- Windows 10 SDK: Ensure the latest version is installed
- PowerToys Repository: Clone from GitHub
### Setup Steps
1. Clone the Repository:
```
git clone https://github.com/microsoft/PowerToys.git
```
2. Open `PowerToys.sln` in Visual Studio
3. Select the Release configuration and build the solution
4. If you encounter build errors, try deleting the x64 output folder and rebuild
## Getting Started with FancyZones Development
### Step 1: Familiarize with the Feature
- Use the feature to understand its functionality
- Read the official documentation: [PowerToys FancyZones utility for Windows](https://learn.microsoft.com/en-us/windows/powertoys/fancyzones)
### Step 2: Build and Debug
- Ensure you can successfully compile and debug the module
- First-time setup may require running the Editor through PowerToys Settings UI to initialize configuration files
### Step 3: Learn through Bug Fixes
- Examine existing bugs and feature requests to understand code structure
- Use debugging to trace code execution for specific features
- Examine UI test code to understand how features are tested
## Debugging
### Setup for Debugging
1. In Visual Studio 2022, set FancyZonesEditor as the startup project
2. Set breakpoints in the code where needed
3. Click Run to start debugging
### During Active Development
- You can perform breakpoint debugging to troubleshoot issues
- Attach to running processes if needed to debug the module in context
### Common Debugging Issues
- If encountering JSON errors on first run, launch the FancyZones Editor once through PowerToys Settings UI to initialize required configuration files
- For UI-related issues, use tools like AccessibilityInsights to inspect element properties
## Deployment and Release Process
### Deployment
#### Local Testing
1. Build the solution in Visual Studio
2. Run PowerToys.exe from the output directory
#### Packaging
- Use the MSIX packaging tool to create an installer
- Ensure all dependencies are included
### Release
#### Versioning
- Follow semantic versioning for releases
#### Release Notes
- Document all changes, fixes, and new features
#### Publishing
1. Create a new release on GitHub
2. Upload the installer and release notes
## Troubleshooting
### First Run JSON Error
**Error**: "The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."
**Solution**: Launch the FancyZones Editor once through PowerToys Settings UI. Running the Editor directly within the project will not initialize the required configuration files.
### Known Issues
- Potential undiscovered bugs related to data updates in the Editor
- Some automated tests pass in CI but fail on specific machines
- Complex testing requirements across different monitor configurations
## FancyZones UI Testing
UI tests are implemented using [Windows Application Driver](https://github.com/microsoft/WinAppDriver).
## Before running tests
### Before running tests
- Install Windows Application Driver v1.2.1 from https://github.com/microsoft/WinAppDriver/releases/tag/v1.2.1.
- Enable Developer Mode in Windows settings
## Running tests
### Running tests
- Exit PowerToys if it's running
- Run WinAppDriver.exe from the installation directory. Skip this step if installed in the default directory (`C:\Program Files (x86)\Windows Application Driver`); in this case, it'll be launched automatically during tests.
@@ -16,11 +249,239 @@ UI tests are implemented using [Windows Application Driver](https://github.com/m
>Note: notifications or other application windows, that are shown above the window under test, can disrupt the testing process.
### UI Test Automation
## Extra tools and information
FancyZones is currently undergoing a UI Test migration process to improve automated testing coverage. You can track the progress of this migration at:
[FancyZones UI Test Migration Progress](https://github.com/microsoft/PowerToys/blob/feature/UITestAutomation/src/modules/fancyzones/UITests-FancyZonesEditor/release-test-checklist.md)
### Testing Strategy
#### Unit Tests
- Build the unit test project
- Run using the Visual Studio Test Explorer (`Test > Test Explorer` or `Ctrl+E, T`)
#### Integration Tests
- Ensure the entire FancyZones module works as expected
- Test different window layouts and snapping behaviors
### Test Framework Structure
#### UI Test Requirements
All test cases require pre-configured user data and must reset this data before each test.
**Required User Data Files**:
- EditorParameters
- AppliedLayouts
- CustomLayouts
- DefaultLayouts
- LayoutHotkeys
- LayoutTemplates
- AppZoneHistory
#### Editor Test Suite
**ApplyLayoutTest.cs**
- Verifies layout application and selection per monitor
- Tests file updates and behavior under display switching
- Validates virtual desktop changes
**CopyLayoutTests.cs**
- Tests copying various layout types
- Validates UI and file correctness
**CreateLayoutTests.cs**
- Tests layout creation and cancellation
- Focuses on file correctness validation
**CustomLayoutsTests.cs**
- Tests user-created layout operations
- Covers renaming, highlight line changes, zone count changes
**DefaultLayoutsTest.cs**
- Validates default and user layout files
**DeleteLayoutTests.cs**
- Tests layout deletion across types
- Checks both UI and file updates
**EditLayoutTests.cs**
- Tests zone operations: add/delete/move/reset/split/merge
**FirstLaunchTest.cs**
- Verifies Editor launches correctly on first run
**LayoutHotkeysTests.cs**
- Tests hotkey configuration file correctness
- Note: Actual hotkey behavior tested in FancyZones backend
**TemplateLayoutsTests.cs**
- Tests operations on built-in layouts
- Covers renaming, highlight changes, zone count changes
#### FancyZones Backend Tests
**LayoutApplyHotKeyTests.cs**
- Focuses on hotkey-related functionality
- Tests actual hotkey behavior implementation
### UI Testing Tools
While working on tests, you may need tools to view element accessibility data:
- [AccessibilityInsights](https://accessibilityinsights.io/docs/windows/overview)
- [WinAppDriver UI Recorder](https://github.com/microsoft/WinAppDriver/wiki/WinAppDriver-UI-Recorder)
>Note: Close helper tools while running tests. Overlapping windows can affect test results.
2. FancyZones might have implemented certain screen resolution limits in the code that do not support such wide screens
3. User error — it can be seen that no layout has been applied to the screen, so it's normal that the far right is not displayed, as the user hasn't used the FancyZones feature
4. From the image, it appears the user is trying to maximize a game window, but some games may not support rendering windows at such high resolutions due to internal implementation
The **optimal solution** for this bug is to first comment on the user's usage issue. Let them correctly use the FancyZones feature before making further judgments. If the issue persists after proper usage, then investigate whether it's a code issue or a problem with the game itself.
To demonstrate a debugging example, I will assume it's a code issue, specifically an issue with the Editor. Please see the following debug process.
Let's first locate the corresponding code. Since the error is in the Editor, we'll start by checking the FancyZonesEditor shown in the image.
![Debug Step Image](../images/fancyzones/1.png)
However, I currently don't know where the code for this specific UI element in the Editor is located.
![Debug Step Image](../images/fancyzones/2.png)
We now have two approaches to find the exact code location.
**First approach:**
The main XAML page is usually named `App.xaml` or `MainWindow.xaml`. Let's start by locating these two files in the FancyZones Editor. Upon reviewing their contents, we find that `App.xaml` is primarily a wrapper file and doesn't contain much UI code. Therefore, it's highly likely that the UI code is located in `MainWindow.xaml`. In the preview of `MainWindow.xaml`, we can also see a rough outline of the UI elements.![Debug Step Image](../images/fancyzones/3.png)
By searching for "monitor", we found that only lines 82 and 338 contain the string "monitor".![Debug Step Image](../images/fancyzones/4.png)
Then, upon reviewing the code, we found that the line at 82 is part of a template. The UI element we're looking for is located within the code block around line 338.
**Second approach:**
We can use the **AccessibilityInsights** tool to inspect the specific information of the corresponding UI element.
![Debug Step Image](../images/fancyzones/5.png)
However, the current UI element does not have an AutomationId. Let's check whether its parent or child nodes have an AutomationId value. (In fact, using ClassName could also help locate it, but elements with the same ClassName might be numerous, making AutomationId a more accurate option.)
![Debug Step Image](../images/fancyzones/6.png)
We found that the parent node "List View" has an AutomationId value. Copy this value and search for it in the code.
![Debug Step Image](../images/fancyzones/7.png)
**Accurately located at line 338.**
Now that we've found the code for the UI element, let's look at where the size data for this UI element comes from. First, the text of this `Text` element is bound within the `MonitorItemTemplate`. The name of this `Text` element is `ResolutionText`, and it binds to a data property named `Dimensions`.
![Debug Step Image](../images/fancyzones/8.png)
Search for code related to `Dimensions` across all projects in FancyZones.
![Debug Step Image](../images/fancyzones/9.png)
We found that this string corresponds to a variable. However, the return value differs in Debug mode, so let's first examine the logic in Release mode.
We found that the variable `ScreenBoundsWidth` is located in the constructor of `MonitorInfoModel`.
![Debug Step Image](../images/fancyzones/10.png)
Then, by searching for `MonitorInfoModel`, we found that this class is instantiated in the constructor of the `MonitorViewModel` class.
![Debug Step Image](../images/fancyzones/11.png)
The width and height of the monitor, which are crucial, are also assigned at this point. Let's continue by checking where the data in `App.Overlay.Monitors` is initialized.
My idea is to examine all references to the `Monitors` variable and identify the initialization point based on those references.
![Debug Step Image](../images/fancyzones/12.png)
Finally, by tracing the `Add` function of `Monitors`, we found the `AddMonitor()` method. This method is only called by `ParseParams()`, which confirms that the data originates from there.
However, by examining the context around the `AddMonitor()` function, we can see that the data comes from the `editor-parameters.json` file. Next, we will continue to investigate how this file is initialized and modified.
![Debug Step Image](../images/fancyzones/13.png)
By searching, we found that the `editor-parameters.json` file has write functions in both the Editor and FancyZones projects.
![Debug Step Image](../images/fancyzones/14.png)
**The display information is retrieved through the following call stack:**
`UpdateWorkAreas()` → `IdentifyMonitors()` → `GetDisplays()` → `EnumDisplayDevicesW()`.
**How was the `UpdateWorkAreas()` function identified?**
It was discovered by searching for `EditorParameters` and noticing that when the `save` function is called on `EditorParameters`, the parameter passed is `m_workAreaConfiguration`.
![Debug Step Image](../images/fancyzones/15.png)
**Then, by checking the initialization location of the `m_workAreaConfiguration` variable, we found that it is initialized inside `UpdateWorkAreas`.**
With this, we have successfully identified the source of the monitor resolution data displayed in the Editor's `Monitors` section.
### Step Four
Familiarize yourself with the module code through the current tasks at hand.
Bug[Issues · microsoftPowerToys](https://github.com/microsoft/PowerToys/issues?q=is%3Aissue%20state%3Aopen%20type%3ABug%20label%3AProduct-FancyZones)
UITest Code
[Task 57329836: PowerToys UI Test FancyZone UI Test Override Windows Snap-1 - Boards](https://microsoft.visualstudio.com/OS/_workitems/edit/57329836/)
[Task 57329843: PowerToys UI Test FancyZone UI Test Override Windows Snap-2 - Boards](https://microsoft.visualstudio.com/OS/_workitems/edit/57329843/)
[Task 57329845: PowerToys UI Test FancyZone UI Test Override Windows Snap-3 - Boards](https://microsoft.visualstudio.com/OS/_workitems/edit/57329845/)
[Task 56940387: PowerToys UI Test FancyZone UI Test Override Windows Snap-4 - Boards](https://microsoft.visualstudio.com/OS/_workitems/edit/56940387/)
UI Test Check List:
PowerToys/doc/releases/tests-checklist-template.md at releaseChecklist · microsoft/PowerToys](https://github.com/microsoft/PowerToys/blob/releaseChecklist/doc/releases/tests-checklist-template.md)
## Q&A
- ### First Run FancyZones error
![Debug Step Image](../images/fancyzones/16.png)
If you encounter this situation, you need to launch the FancyZones Editor once in the powertoys settings UI (Refer to the image below). The reason is that running the Editor directly within the project will not initialize various configuration files.
![Debug Step Image](../images/fancyzones/17.png)
- ### How are layouts stored and loaded? Is there a central configuration handler?
There is no central configuration handler.
Editor read/write config data handler is in FancyZonesEditorCommon project.
![Debug Step Image](../images/fancyzones/18.png)
FancyZones cpp project read/write config data handler is in FancyZonesLib project.
![Debug Step Image](../images/fancyzones/19.png)
However, the files write and read those are C:\Users\“xxxxxx”\AppData\Local\Microsoft\PowerToys\FancyZones
You can think of the editor as a visual config editor, which is most of its functionality. Another feature is used to set the layout for the monitor displays.
When the Editor starts, it will load the config data, and when FancyZones starts, it will also load the config data. After the Editor updates the config data, it will send a data update event, and FancyZones will refresh the current data in memory upon receiving the event.
![Debug Step Image](../images/fancyzones/20.png)
- ### Which parts of the code are responsible for monitor detection and DPI scaling?
About monitor detection you can find "FancyZones::MoveSizeUpdate" function.
I believe that in the case without DPI scaling, FancyZones retrieves the window's position and does not need to know what the mouse's DPI scaling is like. If you are referring to window scaling, it is called through the system interface, and you can see the detailed code in "WindowMouseSnap::MoveSizeEnd()" fucntion.
- ### How does FancyZones track which windows belong to which zones?
In "FancyZones::MoveSizeUpdate" function.
### Extra tools and information
**Test samples**: https://github.com/microsoft/WinAppDriver/tree/master/Samples
While working on tests, you may need a tool that helps you to view the element's accessibility data, e.g. for finding the button to click. For this purpose, you could use [AccessibilityInsights](https://accessibilityinsights.io/docs/windows/overview) or [WinAppDriver UI Recorder](https://github.com/microsoft/WinAppDriver/wiki/WinAppDriver-UI-Recorder).
>Note: close helper tools while running tests. Overlapping windows can affect test results.
>Note: close helper tools while running tests. Overlapping windows can affect test results.

View File

@@ -0,0 +1,34 @@
# File Explorer Add-ons
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/file-explorer)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-File%20Explorer%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-File%20Explorer%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-File+Explorer%22)
## Overview
File Explorer Add-ons are extensions that enhance Windows File Explorer functionality with additional features and context menu options.
## Links
- [Source code folder](https://github.com/microsoft/PowerToys/tree/main/src/modules/fileexplorerpreview)
- [Issue tracker](https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+label%3A%22File+Explorer%22)
## Implementation Details
TODO: Add implementation details
## Debugging
TODO: Add debugging information
## Settings
TODO: Add settings documentation
## Future Improvements
TODO: Add potential future improvements

View File

@@ -0,0 +1,202 @@
# File Locksmith
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/file-locksmith)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-File%20Locksmith%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-File%20Locksmith%22%20label%3AIssue-Bug)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-File+Locksmith%22)
## Overview
File Locksmith is a utility in PowerToys that shows which processes are locking or using a specific file. This helps users identify what's preventing them from deleting, moving, or modifying files by revealing the processes that have handles to those files.
## Architecture
![Diagram](../images/filelocksmith/diagram.png)
File Locksmith follows a similar architecture to the ImageResizer and NewPlus modules. It consists of:
1. **Shell Extensions**:
- `FileLocksmithExt` - COM-based shell extension for Windows 10 and below
- `FileLocksmithContextMenu` - Shell extension for Windows 11 context menu
2. **Core Components**:
- `FileLocksmithLib` - Handles IPC between shell extensions and UI
- `FileLocksmithLibInterop` - Core functionality for finding processes locking files
- `FileLocksmithUI` - WinUI 3 user interface component
3. **Settings Integration**:
- Settings integration in the PowerToys settings application
## Implementation Details
### Shell Extensions
The module adds "Unlock with File Locksmith" to the context menu in File Explorer:
- For Windows 11, a context menu command is registered as a MSIX sparse package (compiled via appxmanifest.xml)
- For Windows 10 and below, a traditional shell extension is registered through registry keys during installation
### Process Communication Flow
1. User enables File Locksmith in PowerToys settings
2. User right-clicks on a file and selects "Unlock with File Locksmith"
3. The shell extension writes the selected file path to a temporary file (file-based IPC)
4. The shell extension launches `PowerToys.FileLocksmithUI.exe`
5. The UI reads the file path from the temporary file
6. The UI uses `FileLocksmithLibInterop` to scan for processes with handles to the file
7. Results are displayed in the UI, showing process information and allowing user action
### Core Functionality
The core functionality to find processes locking files is implemented in [FileLocksmith.cpp](/src/modules/FileLocksmith/FileLocksmithLibInterop/FileLocksmith.cpp), which:
- Uses low-level Windows APIs via `NtdllExtensions` to iterate through file handles
- Examines all running processes to find handles to the specified files
- Maps process IDs to the files they're locking
- Retrieves process information such as name, user context, and file paths
### User Interface
The UI is built with WinUI 3 and uses MVVM architecture:
- View models handle process data and user interactions
- Converters transform raw data into UI-friendly formats
- The interface shows which processes are locking files, along with icons and process details
## Code Structure
### Shell Extensions
- [ClassFactory.cpp](/src/modules/FileLocksmith/FileLocksmithExt/ClassFactory.cpp): COM class factory that creates instances of shell extension objects
- [ExplorerCommand.cpp](/src/modules/FileLocksmith/FileLocksmithExt/ExplorerCommand.cpp): Implements Windows Explorer context menu command for Windows 10 and below
- [PowerToysModule.cpp](/src/modules/FileLocksmith/FileLocksmithExt/PowerToysModule.cpp): PowerToys module interface implementation with settings management
- [dllmain.cpp](/src/modules/FileLocksmith/FileLocksmithExt/dllmain.cpp): DLL entry point for Windows 10 shell extension
- [dllmain.cpp](/src/modules/FileLocksmith/FileLocksmithContextMenu/dllmain.cpp): Windows 11 context menu integration through MSIX package
### Core Libraries
- [IPC.cpp](/src/modules/FileLocksmith/FileLocksmithLib/IPC.cpp): File-based inter-process communication between shell extensions and UI
- [Settings.cpp](/src/modules/FileLocksmith/FileLocksmithLib/Settings.cpp): Settings management for File Locksmith module
- [FileLocksmith.cpp](/src/modules/FileLocksmith/FileLocksmithLibInterop/FileLocksmith.cpp): Core process scanning implementation to find processes locking files
- [NativeMethods.cpp](/src/modules/FileLocksmith/FileLocksmithLibInterop/NativeMethods.cpp): Interop layer bridging native C++ with WinRT-based UI
- [NtdllBase.cpp](/src/modules/FileLocksmith/FileLocksmithLibInterop/NtdllBase.cpp): Interface to native Windows NT APIs
- [NtdllExtensions.cpp](/src/modules/FileLocksmith/FileLocksmithLibInterop/NtdllExtensions.cpp): Process and handle querying utilities using NtQuerySystemInformation
- [ProcessResult.cpp](/src/modules/FileLocksmith/FileLocksmithLibInterop/ProcessResult.cpp): Class for storing process information (name, PID, user, file list)
### UI Components
- [FileCountConverter.cs](/src/modules/FileLocksmith/FileLocksmithUI/Converters/FileCountConverter.cs): Converts file counts for UI display
- [FileListToDescriptionConverter.cs](/src/modules/FileLocksmith/FileLocksmithUI/Converters/FileListToDescriptionConverter.cs): Formats file lists for display
- [PidToIconConverter.cs](/src/modules/FileLocksmith/FileLocksmithUI/Converters/PidToIconConverter.cs): Extracts icons for processes
- [UserToSystemWarningVisibilityConverter.cs](/src/modules/FileLocksmith/FileLocksmithUI/Converters/UserToSystemWarningVisibilityConverter.cs): Shows warnings for system processes
- [MainWindow.xaml.cs](/src/modules/FileLocksmith/FileLocksmithUI/FileLocksmithXAML/MainWindow.xaml.cs): Main application window implementation
- [App.xaml.cs](/src/modules/FileLocksmith/FileLocksmithUI/FileLocksmithXAML/App.xaml.cs): Application entry point
- [ResourceLoaderInstance.cs](/src/modules/FileLocksmith/FileLocksmithUI/Helpers/ResourceLoaderInstance.cs): Localization resource helper
- [MainViewModel.cs](/src/modules/FileLocksmith/FileLocksmithUI/ViewModels/MainViewModel.cs): Main view model that handles loading processes asynchronously
### Settings Integration
- [FileLocksmithViewModel.cs](/src/settings-ui/Settings.UI/ViewModels/FileLocksmithViewModel.cs): ViewModel for File Locksmith in PowerToys settings
- [FileLocksmithLocalProperties.cs](/src/settings-ui/Settings.UI.Library/FileLocksmithLocalProperties.cs): Machine-level settings storage
- [FileLocksmithProperties.cs](/src/settings-ui/Settings.UI.Library/FileLocksmithProperties.cs): User-level settings storage
- [FileLocksmithSettings.cs](/src/settings-ui/Settings.UI.Library/FileLocksmithSettings.cs): Module settings definitions
## Debugging
To build and debug the File Locksmith module:
0. **Build FileLocksmith module**
- Shutdown the existing release builds of PowerToys
- Open the solution in Visual Studio
- Build the entire solution
- Build the `FileLocksmith` project
1. **Create certificate and import to Root (if you don't already have)**
```powershell
New-SelfSignedCertificate -Subject "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" `
-KeyUsage DigitalSignature `
-Type CodeSigningCert `
-FriendlyName "PowerToys SelfCodeSigning" `
-CertStoreLocation "Cert:\CurrentUser\My"
$cert = Get-ChildItem -Path Cert:\CurrentUser\My | Where-Object { $_.FriendlyName -like "*PowerToys*" }
Export-Certificate -Cert $cert -FilePath "$env:TEMP\PowerToysCodeSigning.cer"
# under admin Terminal:
Import-Certificate -FilePath "$env:TEMP\PowerToysCodeSigning.cer" -CertStoreLocation Cert:\LocalMachine\Root
# get Thumbprint
Get-ChildItem -Path Cert:\CurrentUser\My | Where-Object { $_.FriendlyName -like "*PowerToys*" }
```
2. **Sign the MSIX package**
```
SignTool sign /fd SHA256 /sha1 <CERTIFICATE THUMBPRINT> "C:\Users\$env:USERNAME\source\repos\PowerToys\x64\Debug\WinUI3Apps\FileLocksmithContextMenuPackage.msix"
```
SignTool might be not in your PATH, so you may need to specify the full path to it, e.g., `C:\Program Files (x86)\Windows Kits\10\bin\<version>\x64\signtool.exe`.
**commands example**:
```powershell
PS C:\Users\developer> New-SelfSignedCertificate -Subject "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" `
>> -KeyUsage DigitalSignature `
>> -Type CodeSigningCert `
>> -FriendlyName "PowerToys SelfSigned" `
>> -CertStoreLocation "Cert:\CurrentUser\My"
PSParentPath: Microsoft.PowerShell.Security\Certificate::CurrentUser\My
Thumbprint Subject EnhancedKeyUsageList
---------- ------- --------------------
1AA018C2B06B60EAFEE452ADE403306F39058FF5 CN=Microsoft Corpor… Code Signing
PS C:\Users\developer> Get-ChildItem -Path Cert:\CurrentUser\My | Where-Object { $_.FriendlyName -like "*PowerToys*" }
PSParentPath: Microsoft.PowerShell.Security\Certificate::CurrentUser\My
Thumbprint Subject EnhancedKeyUsageList
---------- ------- --------------------
1AA018C2B06B60EAFEE452ADE403306F39058FF5 CN=Microsoft Corpor… Code Signing
PS C:\Users\developer> & "C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\signtool.exe" sign /fd SHA256 /sha1 1AA018C2B06B60EAFEE452ADE403306F39058FF5 "%REPO_PATH%\PowerToys\x64\Debug\WinUI3Apps\FileLocksmithContextMenuPackage.msix"
Done Adding Additional Store
Successfully signed: C:\Users\developer\Develop\GitHub\PowerToys\x64\Debug\WinUI3Apps\FileLocksmithContextMenuPackage.msix
```
3. **Remove old version**
```powershell
Get-AppxPackage -Name Microsoft.PowerToys.FileLocksmithContextMenu*
Remove-AppxPackage Microsoft.PowerToys.FileLocksmithContextMenu_1.0.0.0_neutral__8wekyb3d8bbwe
```
4. **Install new signed MSIX**
```powershell
Add-AppxPackage -Path "%REPO_PATH%\PowerToys\x64\Debug\WinUI3Apps\FileLocksmithContextMenuPackage.msix" -ExternalLocation "%REPO_PATH%\PowerToys\x64\Debug\WinUI3Apps"
```
5. **Restart Explorer**
- Go to Task Manager and restart explorer.exe
6. **Debug Process**
- Set the breakpoint in [dllmain.cpp](/src/modules/FileLocksmith/FileLocksmithContextMenu/dllmain.cpp#L116)
- Open the **Attach to Process** dialog in Visual Studio
- Right-click a file in File Explorer
- Attach the debugger to `dllhost.exe` with **FileLocksmith** Title to debug the shell extension
![Attach to Process](../images/filelocksmith/debug.png)
- Right-click (fast) a file again and select *"Unlock with File Locksmith"*
- Attach the debugger to `PowerToys.FileLocksmithUI.exe` to debug the UI
7. **Alternative Debugging Method**
- You can set the `FileLocksmithUI` as startup project directly in Visual Studio, which will launch the UI without needing to go through the shell extension. This is useful for debugging the UI logic without the shell extension overhead.
## Known Issues
There is an open PR to change the IPC mechanism from file-based to pipe-based, but it has blockers:
- When restarting as admin, the context menu extension doesn't show
- The "Unlock with File Locksmith" option doesn't work when launched as admin
## Settings Integration
File Locksmith integrates with the PowerToys settings through:
- [FileLocksmithViewModel.cs](/src/settings-ui/Settings.UI/ViewModels/FileLocksmithViewModel.cs)
- [FileLocksmithLocalProperties.cs](/src/settings-ui/Settings.UI.Library/FileLocksmithLocalProperties.cs)
- [FileLocksmithProperties.cs](/src/settings-ui/Settings.UI.Library/FileLocksmithProperties.cs)
- [FileLocksmithSettings.cs](/src/settings-ui/Settings.UI.Library/FileLocksmithSettings.cs)

View File

@@ -0,0 +1,114 @@
# Hosts File Editor
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/hosts-file-editor)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Hosts%20File%20Editor%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Hosts%20File%20Editor%22%20label%3AIssue-Bug)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-Hosts+File+Editor%22)
## Overview
The Hosts File Editor module provides a convenient way to edit the system's hosts file. The hosts file is a plain text file used by the operating system to map hostnames to IP addresses, allowing users to override DNS for specific domain names.
## Code Structure
![Diagram](../images/hostsfileeditor/diagram.png)
The Hosts File Editor module is structured into three primary components:
1. **Hosts** - Entry point for the Hosts File Editor. Manages core services and settings through helper utilities.
2. **HostsModuleInterface** - Interface for integrating the Hosts module with the PowerToys system.
3. **HostsUILib** - Implements the UI layer using WinUI 3.
This structure is similar to the Environment Variables for Windows module.
## Key Components
### Main Entry Points
- **Module Entry**: [Program.cs](/src/modules/Hosts/Program.cs) → [App.xaml.cs](/src/modules/Hosts/HostsXAML/App.xaml.cs)
- **Settings UI**:
- Main Window: [MainWindow.xaml.cs](/src/modules/Hosts/Hosts/HostsXAML/MainWindow.xaml.cs)
- View: [HostsMainPage.xaml](/src/modules/Hosts/HostsUILib/HostsMainPage.xaml)
- ViewModel: [HostsMainPage.xaml.cs](/src/modules/Hosts/HostsUILib/HostsMainPage.xaml.cs)
- **Runner Integration**: [HostsModuleInterface](/src/modules/Hosts/HostsModuleInterface)
### Runner Integration
The module is loaded by the PowerToys runner from:
- [main.cpp](/src/runner/main.cpp) (Lines 183-184): Loads Hosts Module using `L"WinUI3Apps/PowerToys.HostsModuleInterface.dll"`
### Settings Management
- [HostsViewModel.cs](/src/settings-ui/Settings.UI/ViewModels/HostsViewModel.cs): Hosts UI in PowerToys settings
- [HostsProperties.cs](/src/settings-ui/Settings.UI.Library/HostsProperties.cs): In settings UI
- [HostsSettings.cs](/src/settings-ui/Settings.UI.Library/HostsSettings.cs): Wrapper with HostsProperties
### Module Components
#### HostsModuleInterface
- Defines the interface for integrating the Hosts module with the PowerToys system.
#### Hosts (Main Project)
- [Program.cs](/src/modules/Hosts/Hosts/Program.cs): Launch app
- [HostsXAML](/src/modules/Hosts/Hosts/HostsXAML): Initialize service and loads the main window
- [Host.cs](/src/modules/Hosts/Hosts/Helpers/Host.cs): Access to services register
- [NativeEventWaiter.cs](/src/modules/Hosts/Hosts/Helpers/NativeEventWaiter.cs): Gets the dispatcher queue for posting UI updates from a background thread
- [UserSettings.cs](/src/modules/Hosts/Hosts/Settings/UserSettings.cs): Manages reading, tracking, and updating user settings from settings.json
#### HostsUILib
- [HostsMainPage.xaml.cs](/src/modules/Hosts/HostsUILib/HostsMainPage.xaml.cs): Main page
- [ViewModels](/src/modules/Hosts/HostsUILib/ViewModels): Contains view models that manage state and logic
- [Models](/src/modules/Hosts/HostsUILib/Models): Models for managing host entries
- [AddressType.cs](/src/modules/Hosts/HostsUILib/Models/AddressType.cs): Specifies whether an address is IPv4, IPv6, or Invalid
- [Entry.cs](/src/modules/Hosts/HostsUILib/Models/Entry.cs): Represents a single hosts file entry (IP address, hostnames, comment, flags)
- [HostsData.cs](/src/modules/Hosts/HostsUILib/Models/HostsData.cs): Converts the list of entries into a read-only collection
- [Settings](/src/modules/Hosts/HostsUILib/Settings): Settings configuration
- [Consts.cs](/src/modules/Hosts/HostsUILib/Consts.cs): Defines constants like max hosts IP length
- [Helpers](/src/modules/Hosts/HostsUILib/Helpers): Utilities for dealing with hosts IP, filter features, and file loading
## Call Flow
1. **Enable app**: runner/main.cpp → settings.ui/settings.ui.library
2. **Start app**: Program.cs → HostsXAML → HostsMainPage
3. **Load hosts data**: ViewModel → HostsData → Helpers (load and parse file)
4. **User edits**: UI bound to ViewModel updates entries
5. **Save changes**: ViewModel triggers file write through Helpers
6. **Settings management**: UserSettings.cs persists user preferences
## Key Features
| Feature | Key Function |
|---------|--------------|
| Adding a new entry | `Add(Entry entry)` |
| Filtering host file entries | `ApplyFilters()` |
| Open Hosts File | `ReadHosts()` |
| Additional Lines | `UpdateAdditionalLines(string lines)` |
## Settings
| Setting | Implementation |
|---------|---------------|
| Open as administrator | `UserSettings()` |
| Additional lines position | `UserSettings()->AdditionalLinesPosition` |
| Consider loopback addresses as duplicates | `UserSettings()->LoopbackDuplicates` |
| Encoding Setting | `UserSettings()->Encoding` |
## UI Test Automation
Hosts File Editor is currently undergoing a UI Test migration process to improve automated testing coverage. You can track the progress of this migration at:
[Hosts File Editor UI Test Migration Progress](https://github.com/microsoft/PowerToys/blob/feature/UITestAutomation/src/modules/Hosts/Hosts.UITests/Release-Test-Checklist-Migration-Progress.md)
## How to Build and Debug
1. Build PowerToys Project in debug mode
2. Set Hosts as the startup project
3. Launch Hosts File Editor in debug mode
4. Attach the debugger to PowerToys.Hosts.dll
5. Add breakpoints in the Hosts code

View File

@@ -0,0 +1,132 @@
# Image Resizer
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/image-resizer)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Image%20Resizer%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-Image%20Resizer%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-Image+Resizer%22)
Image Resizer is a Windows shell extension that enables batch resizing of images directly from File Explorer.
## Overview
Image Resizer provides a convenient way to resize images without opening a dedicated image editing application. It is accessible through the Windows context menu and allows users to:
- Resize single or multiple images at once
- Choose from predefined sizing presets or enter custom dimensions
- Maintain or modify aspect ratios
- Create copies or overwrite original files
- Apply custom filename formats to resized images
- Select different encoding quality settings
## Architecture
Image Resizer consists of multiple components:
- Shell Extension DLL (context menu integration)
- WinUI 3 UI application
- Core image processing library
### Technology Stack
- C++/WinRT
- WPF (UI components)
- Windows Imaging Component (WIC) for image processing
- COM for shell integration
## Context Menu Integration
Image Resizer integrates with the Windows context menu following the [PowerToys Context Menu Handlers](../common/context-menus.md) pattern. It uses a dual registration approach to ensure compatibility with both Windows 10 and Windows 11.
### Registration Process
The context menu integration follows the same pattern as PowerRename, using:
- A traditional shell extension for Windows 10
- A sparse MSIX package for Windows 11 context menus
For more details on the implementation approach, see the [Dual Registration section](../common/context-menus.md#1-dual-registration-eg-imageresizer-powerrename) in the context menu documentation.
### Context Menu Appearance Logic
Image Resizer dynamically determines when to show the context menu option:
- `AppxManifest.xml` registers the extension for all file types (`Type="*"`)
- The shell extension checks if the selected files are images using `AssocGetPerceivedType()`
- The menu appears only for image files (returns `ECS_ENABLED`), otherwise it remains hidden (returns `ECS_HIDDEN`)
This approach provides flexibility to support additional file types by modifying only the detection logic without changing the system-level registration.
## UI Implementation
Image Resizer uses WPF for its user interface, as evidenced by the App.xaml.cs file. The UI allows users to:
- Select from predefined size presets or enter custom dimensions
- Configure filename format for the resized images
- Set encoding quality and format options
- Choose whether to replace or create copies of the original files
From the App.xaml.cs file, we can see that the application:
- Supports localization through `LanguageHelper.LoadLanguage()`
- Processes command line arguments via `ResizeBatch.FromCommandLine()`
- Uses a view model pattern with `MainViewModel`
- Respects Group Policy settings via `GPOWrapper.GetConfiguredImageResizerEnabledValue()`
## Debugging
### Debugging the Context Menu
See the [Debugging Context Menu Handlers](../common/context-menus.md#debugging-context-menu-handlers) section for general guidance on debugging PowerToys context menu extensions.
For Image Resizer specifically, there are several approaches:
#### Option 1: Manual Registration via Registry
1. Create a registry file (e.g., `register.reg`) with the following content:
```
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\CLSID\{51B4D7E5-7568-4234-B4BB-47FB3C016A69}]
@="PowerToys Image Resizer Extension"
[HKEY_CLASSES_ROOT\CLSID\{51B4D7E5-7568-4234-B4BB-47FB3C016A69}\InprocServer32]
@="D:\\PowerToys\\x64\\Debug\\PowerToys.ImageResizerExt.dll"
"ThreadingModel"="Apartment"
[HKEY_CURRENT_USER\Software\Classes\SystemFileAssociations\.png\ShellEx\ContextMenuHandlers\ImageResizer]
@="{51B4D7E5-7568-4234-B4BB-47FB3C016A69}"
```
2. Import the registry file:
```
reg import register.reg
```
3. Restart Explorer to apply changes:
```
taskkill /f /im explorer.exe && start explorer.exe
```
4. Attach the debugger to `explorer.exe`
5. Add breakpoints to relevant code in the Image Resizer shell extension
#### Option 2: Using regsvr32
1. Register the shell extension DLL:
```
regsvr32 "D:\PowerToys\x64\Debug\PowerToys.ImageResizerExt.dll"
```
2. Restart Explorer and attach the debugger as in Option 1
### Common Issues
- Context menu not appearing:
- Ensure the extension is properly registered
- Verify you're right-clicking on supported image files
- Restart Explorer to clear context menu cache
- For Windows 11, check AppX package registration:
- Use `get-appxpackage -Name *imageresizer*` to verify installation
- Use `Remove-AppxPackage` to remove problematic registrations
- Missing UI or processing failures:
- Check Event Viewer for application errors
- Verify file permissions for both source and destination folders

View File

@@ -1,6 +1,17 @@
# Table of Contents
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/keyboard-manager)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Keyboard%20Shortcut%20Manager%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-Keyboard%20Shortcut%20Manager%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-Keyboard+Shortcut+Manager%22+)
The devdocs for Keyboard Manager have been divided into the following modules:
1. [Keyboard Manager Module](keyboardmanager.md)
2. [Keyboard Event Handlers](keyboardeventhandlers.md)
3. [Keyboard Manager UI](keyboardmanagerui.md)
4. [Keyboard Manager Common](keyboardmanagercommon.md)
4. [Keyboard Manager Common](keyboardmanagercommon.md)
5. [Debugging Guide](debug.md)

View File

@@ -0,0 +1,94 @@
# Keyboard Manager Debugging Guide
This document provides guidance on debugging the Keyboard Manager module in PowerToys.
## Module Overview
Keyboard Manager consists of two main components:
- **Keyboard Manager Editor**: UI application for configuring key and shortcut remappings
- **Keyboard Manager Engine**: Background process that intercepts and handles keyboard events
## Development Environment Setup
1. Clone the PowerToys repository
2. Open `PowerToys.sln` in Visual Studio
3. Ensure all NuGet packages are restored
4. Build the entire solution in Debug configuration
## Debugging the Editor (UI)
### Setup
1. In Visual Studio, right-click on the `KeyboardManagerEditor` project
2. Select "Set as Startup Project"
### Common Debugging Scenarios
#### UI Rendering Issues
Breakpoints to consider:
- `EditKeyboardWindow.cpp`: `CreateWindow()` method
- `EditShortcutsWindow.cpp`: `CreateWindow()` method
#### Configuration Changes
When debugging configuration changes:
1. Set breakpoints in `KeyboardManagerState.cpp` around the `SetRemappedKeys()` or `SetRemappedShortcuts()` methods
2. Monitor the JSON serialization process in the save functions
### Testing UI Behavior
The `KeyboardManagerEditorTest` project contains tests for the UI functionality. Run these tests to validate UI changes.
## Debugging the Engine (Remapping Logic)
### Setup
1. In Visual Studio, right-click on the `KeyboardManagerEngine` project
2. Select "Set as Startup Project"
3. Press F5 to start debugging
### Key Event Flow
The keyboard event processing follows this sequence:
1. Low-level keyboard hook captures an event
2. `KeyboardEventHandlers.cpp` processes the event
3. `KeyboardManager.cpp` applies remapping logic
4. Event is either suppressed, modified, or passed through
### Breakpoints to Consider
- `main.cpp`: `StartLowlevelKeyboardHook()` - Hook initialization
- `KeyboardEventHandlers.cpp`: `HandleKeyboardEvent()` - Entry point for each keyboard event
- `KeyboardManager.cpp`: `HandleKeyEvent()` - Processing individual key events
- `KeyboardManager.cpp`: `HandleShortcutRemapEvent()` - Processing shortcut remapping
### Logging and Trace
Enable detailed logging by setting the `_DEBUG` and `KBM_VERBOSE_LOGGING` preprocessor definitions.
## Common Issues and Troubleshooting
### Multiple Instances
If you encounter issues with multiple instances, check the mutex logic in `KeyboardManagerEditor.cpp`. The editor uses `PowerToys_KBMEditor_InstanceMutex` to ensure single instance.
### Key Events Not Being Intercepted
1. Verify the hook is properly installed by setting a breakpoint in the hook procedure
2. Check if any other application is capturing keyboard events at a lower level
3. Ensure the correct configuration is being loaded from the settings JSON
### UI Freezes or Crashes
1. Check XAML Islands initialization in the Editor
2. Verify UI thread is not being blocked by IO operations
3. Look for exceptions in the event handling code
## Advanced Debugging
### Debugging Both Components Simultaneously
To debug both the Editor and Engine:
1. Launch the Engine first in debug mode
2. Attach the debugger to the Editor process when it starts

View File

@@ -0,0 +1,95 @@
# Find My Mouse
Find My Mouse is a utility that helps users locate their mouse pointer by creating a spotlight effect when activated. It is based on Raymond Chen's SuperSonar utility.
## Implementation
Find My Mouse displays a spotlight effect centered on the cursor location when activated via a keyboard shortcut (typically a double-press of the Ctrl key).
### Key Files
- `src/modules/MouseUtils/FindMyMouse/FindMyMouse.cpp` - Contains the main implementation
- Key function: `s_WndProc` - Handles window messages for the utility
### Enabling Process
When the utility is enabled:
1. A background thread is created to run the Find My Mouse logic asynchronously:
```cpp
// Enable the PowerToy
virtual void enable()
{
m_enabled = true; // Mark the module as enabled
Trace::EnableFindMyMouse(true); // Enable telemetry
std::thread([=]() { FindMyMouseMain(m_hModule, m_findMyMouseSettings); }).detach(); // Run main logic in background
}
```
2. The `CompositionSpotlight` instance is initialized with user settings:
```cpp
CompositionSpotlight sonar;
sonar.ApplySettings(settings, false); // Apply settings
if (!sonar.Initialize(hinst))
{
Logger::error("Couldn't initialize a sonar instance.");
return 0;
}
m_sonar = &sonar;
```
3. The utility listens for raw input events using `WM_INPUT`, which provides more precise and responsive input detection than standard mouse events.
### Activation Process
The activation process works as follows:
1. **Keyboard Hook Detects Shortcut**
- A global low-level keyboard hook is set up during initialization
- The hook monitors for the specific activation pattern (double Ctrl press)
- Once matched, it sends a `WM_PRIV_SHORTCUT` message to the sonar window:
```cpp
virtual void OnHotkeyEx() override
{
Logger::trace("OnHotkeyEx()");
HWND hwnd = GetSonarHwnd();
if (hwnd != nullptr)
{
PostMessageW(hwnd, WM_PRIV_SHORTCUT, NULL, NULL);
}
}
```
2. **Message Handler Triggers Action**
- The custom message is routed to `BaseWndProc()`
- The handler toggles the sonar animation:
```cpp
if (message == WM_PRIV_SHORTCUT)
{
if (m_sonarStart == NoSonar)
StartSonar(); // Trigger sonar animation
else
StopSonar(); // Cancel if already running
}
```
3. **Sonar Animation**
- `StartSonar()` uses `CompositionSpotlight` to display a highlight (ripple/pulse) centered on the mouse pointer
- The animation is temporary and fades automatically or can be cancelled by user input
### Event Handling
The Find My Mouse utility handles several types of events:
- **Mouse Events**: Trigger sonar animations (e.g., after a shake or shortcut)
- **Keyboard Events**: May cancel or toggle the effect
- **Custom Shortcut Messages**: Handled to allow toggling Find My Mouse using a user-defined hotkey
When the main window receives a `WM_DESTROY` message (on shutdown or disable), the sonar instance is properly cleaned up, and the message loop ends gracefully.
## Debugging
To debug Find My Mouse:
- Attach to the PowerToys Runner process directly
- Set breakpoints in the `FindMyMouse.cpp` file
- When debugging the spotlight effect, visual artifacts may occur due to the debugger's overhead

View File

@@ -0,0 +1,92 @@
# Mouse Highlighter
Mouse Highlighter is a utility that visualizes mouse clicks by displaying a highlight effect around the cursor when clicked.
## Implementation
Mouse Highlighter runs within the PowerToys Runner process and draws visual indicators (typically circles) around the mouse cursor when the user clicks.
### Key Files
- `src/modules/MouseUtils/MouseHighlighter/MouseHighlighter.cpp` - Contains the main implementation
- Key function: `WndProc` - Handles window messages and mouse events
### Enabling Process
When the utility is enabled:
1. A background thread is created to run the mouse highlighter logic asynchronously:
```cpp
std::thread([=]() { MouseHighlighterMain(m_hModule, m_highlightSettings); }).detach();
```
2. The Highlighter instance is initialized and configured with user settings:
```cpp
Highlighter highlighter;
Highlighter::instance = &highlighter;
highlighter.ApplySettings(settings);
highlighter.MyRegisterClass(hInstance);
```
3. A highlighter window is created:
```cpp
instance->CreateHighlighter();
```
4. The utility:
- Registers a custom window class
- Creates a transparent window for drawing visuals
- Handles the `WM_CREATE` message to initialize the Windows Composition API (Compositor, visuals, and target)
### Activation Process
The activation process works as follows:
1. **Shortcut Detection**
- The system detects when the activation shortcut is pressed
- A global hotkey listener (registered with `RegisterHotKey` or similar hook) detects the shortcut
2. **Message Transmission**
- A message (like `WM_SWITCH_ACTIVATION_MODE`) is sent to the highlighter window via `PostMessage()` or `SendMessage()`
3. **Window Procedure Handling**
- The `WndProc` of the highlighter window receives the message and toggles between start and stop drawing modes:
```cpp
case WM_SWITCH_ACTIVATION_MODE:
if (instance->m_visible)
instance->StopDrawing();
else
instance->StartDrawing();
```
4. **Drawing Activation**
- If turning ON, `StartDrawing()` is called, which:
- Moves the highlighter window to the topmost position
- Slightly offsets the size to avoid transparency bugs
- Shows the transparent drawing window
- Hooks into global mouse events
- Starts drawing visual feedback around the mouse
- If turning OFF, `StopDrawing()` is called, which:
- Hides the drawing window
- Removes the mouse hook
- Stops rendering highlighter visuals
### Drawing Process
When the mouse highlighter is active:
1. A low-level mouse hook detects mouse button events
2. On click, the highlighter draws a circle (or other configured visual) at the cursor position
3. The visual effect fades over time according to user settings
4. Each click can be configured to show different colors based on the mouse button used
## Debugging
To debug Mouse Highlighter:
- Attach to the PowerToys Runner process directly
- Set breakpoints in the `MouseHighlighter.cpp` file
- Be aware that visual effects may appear different or stuttery during debugging due to the debugger's overhead
## Known Issues
- There is a reported bug where the highlight color stays on after toggling opacity to 0
- This issue has been present for more than six months and can still be reproduced in recent PowerToys releases

View File

@@ -0,0 +1,90 @@
# Mouse Jump
Mouse Jump is a utility that allows users to quickly move their cursor to any location on screen using a grid-based overlay interface.
## Implementation
Unlike the other Mouse Utilities that run within the PowerToys Runner process, Mouse Jump operates as a separate process that communicates with the Runner via events.
### Key Files
- `src/modules/MouseUtils/MouseJump` - Contains the Runner interface for Mouse Jump
- `src/modules/MouseUtils/MouseJumpUI` - Contains the UI implementation
- `src/modules/MouseUtils/MouseJumpUI/MainForm.cs` - Main UI form implementation
- `src/modules/MouseUtils/MouseJump.Common` - Shared code between the Runner and UI components
### Enabling Process
When the utility is enabled:
1. A separate UI process is launched for Mouse Jump:
```cpp
void launch_process()
{
Logger::trace(L"Starting MouseJump process");
unsigned long powertoys_pid = GetCurrentProcessId();
std::wstring executable_args = L"";
executable_args.append(std::to_wstring(powertoys_pid));
SHELLEXECUTEINFOW sei{ sizeof(sei) };
sei.fMask = { SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI };
sei.lpFile = L"PowerToys.MouseJumpUI.exe";
sei.nShow = SW_SHOWNORMAL;
sei.lpParameters = executable_args.data();
if (ShellExecuteExW(&sei))
{
Logger::trace("Successfully started the Mouse Jump process");
}
else
{
Logger::error(L"Mouse Jump failed to start. {}", get_last_error_or_default(GetLastError()));
}
m_hProcess = sei.hProcess;
}
```
2. The Runner creates shared events for communication with the UI process:
```cpp
m_hInvokeEvent = CreateDefaultEvent(CommonSharedConstants::MOUSE_JUMP_SHOW_PREVIEW_EVENT);
m_hTerminateEvent = CreateDefaultEvent(CommonSharedConstants::TERMINATE_MOUSE_JUMP_SHARED_EVENT);
```
### Activation Process
The activation process works as follows:
1. **Shortcut Detection**
- When the activation shortcut is pressed, the Runner signals the shared event `MOUSE_JUMP_SHOW_PREVIEW_EVENT`
2. **UI Display**
- The MouseJumpUI process listens for this event and displays a screen overlay when triggered
- The overlay shows a grid or other visual aid to help select a destination point
3. **Mouse Movement**
- User selects a destination point on the overlay
- The UI process moves the mouse cursor to the selected position
4. **Termination**
- When the utility needs to be disabled or PowerToys is shutting down, the Runner signals the `TERMINATE_MOUSE_JUMP_SHARED_EVENT`
- The UI process responds by cleaning up and exiting
### User Interface
The Mouse Jump UI is implemented in C# using Windows Forms:
- Displays a semi-transparent overlay over the entire screen
- May include grid lines, quadrant divisions, or other visual aids to help with precision selection
- Captures mouse and keyboard input to allow for selection and cancellation
- Moves the mouse cursor to the selected location upon confirmation
## Debugging
To debug Mouse Jump:
1. Start by debugging the Runner process directly
2. Then attach the debugger to the MouseJumpUI process when it launches
3. Note: Debugging MouseJumpUI directly is challenging because it requires the Runner's process ID to be passed as a parameter at launch
## Community Contributions
Mouse Jump was initially contributed by Michael Clayton (@mikeclayton) and is based on his FancyMouse utility.

View File

@@ -0,0 +1,114 @@
# Mouse Pointer Crosshairs
Mouse Pointer Crosshairs is a utility that displays horizontal and vertical lines that intersect at the mouse cursor position, making it easier to track the cursor location on screen.
## Implementation
Mouse Pointer Crosshairs runs within the PowerToys Runner process and draws crosshair lines that follow the cursor in real-time.
### Key Files
- `src/modules/MouseUtils/MousePointerCrosshairs/InclusiveCrosshairs.cpp` - Contains the main implementation
- Key function: `WndProc` - Handles window messages and mouse events
### Enabling Process
When the utility is enabled:
1. A background thread is created to run the crosshairs logic asynchronously:
```cpp
std::thread([=]() { InclusiveCrosshairsMain(hInstance, settings); }).detach();
```
2. The InclusiveCrosshairs instance is initialized and configured with user settings:
```cpp
InclusiveCrosshairs crosshairs;
InclusiveCrosshairs::instance = &crosshairs;
crosshairs.ApplySettings(settings, false);
crosshairs.MyRegisterClass(hInstance);
```
3. The utility:
- Creates the crosshairs visuals using Windows Composition API inside `CreateInclusiveCrosshairs()`
- Handles the `WM_CREATE` message to initialize the Windows Composition API (Compositor, visuals, and target)
- Creates a transparent, layered window for drawing the crosshairs with specific extended window styles (e.g., `WS_EX_LAYERED`, `WS_EX_TRANSPARENT`)
### Activation Process
The activation process works as follows:
1. **Shortcut Detection**
- When the activation shortcut is pressed, the window procedure (`WndProc`) receives a custom message `WM_SWITCH_ACTIVATION_MODE`
2. **Toggle Drawing State**
```cpp
case WM_SWITCH_ACTIVATION_MODE:
if (instance->m_drawing)
{
instance->StopDrawing();
}
else
{
instance->StartDrawing();
}
break;
```
3. **Start Drawing Function**
- The `StartDrawing()` function is called to:
- Log the start of drawing
- Update the crosshairs position
- Check if the cursor should be auto-hidden, and set a timer for auto-hide if enabled
- Show the crosshairs window if the cursor is visible
- Set a low-level mouse hook to track mouse movements asynchronously
```cpp
void InclusiveCrosshairs::StartDrawing()
{
Logger::info("Start drawing crosshairs.");
UpdateCrosshairsPosition();
m_hiddenCursor = false;
if (m_crosshairs_auto_hide)
{
CURSORINFO cursorInfo{};
cursorInfo.cbSize = sizeof(cursorInfo);
if (GetCursorInfo(&cursorInfo))
{
m_hiddenCursor = !(cursorInfo.flags & CURSOR_SHOWING);
}
SetAutoHideTimer();
}
if (!m_hiddenCursor)
{
ShowWindow(m_hwnd, SW_SHOWNOACTIVATE);
}
m_drawing = true;
m_mouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, m_hinstance, 0);
}
```
4. **Stop Drawing Function**
- The `StopDrawing()` function is called to:
- Remove the mouse hook
- Kill the auto-hide timer
- Hide the crosshairs window
- Log the stop of drawing
### Cursor Tracking
While active, the utility:
1. Uses a low-level mouse hook (`WH_MOUSE_LL`) to track cursor movement
2. Updates crosshair positions in real-time as the mouse moves
3. Supports auto-hiding functionality when the cursor is inactive for a specified period
## Debugging
To debug Mouse Pointer Crosshairs:
- Attach to the PowerToys Runner process directly
- Set breakpoints in the `InclusiveCrosshairs.cpp` file
- Be aware that during debugging, moving the mouse may cause unexpected or "strange" visual behavior because:
- The mouse hook (`MouseHookProc`) updates the crosshairs position on every `WM_MOUSEMOVE` event
- This frequent update combined with the debugger's overhead or breakpoints can cause visual glitches or stutters

View File

@@ -0,0 +1,129 @@
# Mouse Utilities
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/mouse-utilities)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Mouse%20Utilities%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-Mouse%20Utilities%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-Mouse+Utilities%22)
Mouse Utilities is a collection of tools designed to enhance mouse and cursor functionality on Windows. The module contains four sub-utilities that provide different mouse-related features.
## Overview
Mouse Utilities includes the following sub-modules:
- **[Find My Mouse](findmymouse.md)**: Helps locate the mouse pointer by creating a visual spotlight effect when activated
- **[Mouse Highlighter](mousehighlighter.md)**: Visualizes mouse clicks with customizable highlights
- **[Mouse Jump](mousejump.md)**: Allows quick cursor movement to specific screen locations
- **[Mouse Pointer Crosshairs](mousepointer.md)**: Displays crosshair lines that follow the mouse cursor
## Architecture
Most of the sub-modules (Find My Mouse, Mouse Highlighter, and Mouse Pointer Crosshairs) run within the PowerToys Runner process as separate threads. Mouse Jump is more complex and runs as a separate process that communicates with the Runner via events.
### Code Structure
#### Settings UI
- [MouseUtilsPage.xaml](/src/settings-ui/Settings.UI/SettingsXAML/Views/MouseUtilsPage.xaml)
- [MouseJumpPanel.xaml](/src/settings-ui/Settings.UI/SettingsXAML/Panels/MouseJumpPanel.xaml)
- [MouseJumpPanel.xaml.cs](/src/settings-ui/Settings.UI/SettingsXAML/Panels/MouseJumpPanel.xaml.cs)
- [MouseUtilsViewModel.cs](/src/settings-ui/Settings.UI/ViewModels/MouseUtilsViewModel.cs)
- [MouseUtilsViewModel_MouseJump.cs](/src/settings-ui/Settings.UI/ViewModels/MouseUtilsViewModel_MouseJump.cs)
#### Runner and Module Implementation
- [FindMyMouse](/src/modules/MouseUtils/FindMyMouse)
- [MouseHighlighter](/src/modules/MouseUtils/MouseHighlighter)
- [MousePointerCrosshairs](/src/modules/MouseUtils/MousePointerCrosshairs)
- [MouseJump](/src/modules/MouseUtils/MouseJump)
- [MouseJumpUI](/src/modules/MouseUtils/MouseJumpUI)
- [MouseJump.Common](/src/modules/MouseUtils/MouseJump.Common)
## Community Contributors
- **Michael Clayton (@mikeclayton)**: Contributed the initial version of the Mouse Jump tool and several updates based on his FancyMouse utility
- **Raymond Chen (@oldnewthing)**: Find My Mouse is based on Raymond Chen's SuperSonar
## Known Issues
- Mouse Highlighter has a reported bug where the highlight color stays on after toggling opacity to 0
## UI Test Automation
Mouse Utilities is currently undergoing a UI Test migration process to improve automated testing coverage. You can track the progress of this migration at:
[Mouse Utils UI Test Migration Progress](https://github.com/microsoft/PowerToys/blob/feature/UITestAutomation/src/modules/MouseUtils/MouseUtils.UITests/Release-Test-Checklist-Migration-Progress.md)
## See Also
For more detailed implementation information, please refer to the individual utility documentation pages linked above.
#### Activation Process
1. A keyboard hook detects the activation shortcut (typically double-press of Ctrl)
2. A `WM_PRIV_SHORTCUT` message is sent to the sonar window
3. `StartSonar()` is called to display a spotlight animation centered on the mouse pointer
4. The animation automatically fades or can be cancelled by user input
### Mouse Highlighter
Mouse Highlighter visualizes mouse clicks by displaying a highlight effect around the cursor when clicked.
#### Key Components
- Uses Windows Composition API for rendering
- Main implementation in `MouseHighlighter.cpp`
- Core logic handled by the `WndProc` function
#### Activation Process
1. When activated, it creates a transparent overlay window
2. A mouse hook monitors for click events
3. On click detection, the highlighter draws a circle or other visual indicator
4. The highlight effect fades over time based on user settings
### Mouse Pointer Crosshairs
Displays horizontal and vertical lines that intersect at the mouse cursor position.
#### Key Components
- Uses Windows Composition API for rendering
- Core implementation in `InclusiveCrosshairs.cpp`
- Main logic handled by the `WndProc` function
#### Activation Process
1. Creates a transparent, layered window for drawing crosshairs
2. When activated via shortcut, calls `StartDrawing()`
3. Sets a low-level mouse hook to track cursor movement
4. Updates crosshairs position on every mouse movement
5. Includes auto-hide functionality for cursor inactivity
### Mouse Jump
Allows quick mouse cursor repositioning to any screen location through a grid-based UI.
#### Key Components
- Runs as a separate process (`PowerToys.MouseJumpUI.exe`)
- Communicates with Runner process via events
- UI implemented in `MainForm.cs`
#### Activation Process
1. When shortcut is pressed, Runner triggers the shared event `MOUSE_JUMP_SHOW_PREVIEW_EVENT`
2. The MouseJumpUI process displays a screen overlay
3. User selects a destination point on the overlay
4. Mouse cursor is moved to the selected position
5. The UI process can be terminated via the `TERMINATE_MOUSE_JUMP_SHARED_EVENT`
## Debugging
### Find My Mouse, Mouse Highlighter, and Mouse Pointer Crosshairs
- Debug by attaching to the Runner process directly
- Set breakpoints in the respective utility code files (e.g., `FindMyMouse.cpp`, `MouseHighlighter.cpp`, `InclusiveCrosshairs.cpp`)
- Call the respective utility by using the activation shortcut (e.g., double Ctrl press for Find My Mouse)
- During debugging, visual effects may appear glitchy due to the debugger's overhead
### Mouse Jump
- Start by debugging the Runner process
- Then attach the debugger to the MouseJumpUI process
- Note: Debugging MouseJumpUI directly is challenging as it requires the Runner's process ID as a parameter
## Known Issues
- Mouse Highlighter has a reported bug where the highlight color stays on after toggling opacity to 0

View File

@@ -1,4 +1,13 @@
# Mouse Without Borders module
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/mouse-without-borders)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Mouse%20Without%20Borders%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-Mouse%20Without%20Borders%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-Mouse+Without+Borders%22)
This file contains the documentation for the Mouse Without Borders PowerToy module.
## Table of Contents:
- [Mouse Without Borders module](#mouse-without-borders-module)

View File

@@ -0,0 +1,143 @@
# NewPlus Module
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/newplus)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AProduct-New%2B)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3AProduct-New%2B)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3AProduct-New%2B+)
## Overview
NewPlus is a PowerToys module that provides a context menu entry for creating new files directly from File Explorer. Unlike some other modules, NewPlus implements a different approach to context menu registration to avoid duplication issues in Windows 11.
## Context Menu Implementation
NewPlus implements two separate context menu handlers:
1. **Windows 10 Handler** (`NewPlus.ShellExtension.win10.dll`)
- Implements "old-style" context menu handler for Windows 10 compatibility
- Not shown in Windows 11 (this is intentional and controlled by a condition in `QueryContextMenu`)
- Registered via registry keys
2. **Windows 11 Handler** (`NewPlus.ShellExtension.dll`)
- Implemented as a sparse MSIX package for Windows 11's modern context menu
- Only registered and used on Windows 11
This implementation differs from some other modules like ImageResizer which register both handlers on Windows 11, resulting in duplicate menu entries. NewPlus uses selective registration to provide a cleaner user experience, though it can occasionally lead to issues if the Windows 11 handler fails to register properly.
## Project Structure
- **NewPlus.ShellExtension** - Windows 11 context menu handler implementation
- **NewPlus.ShellExtension.win10** - Windows 10 "old-style" context menu handler implementation
## Debugging NewPlus Context Menu Handlers
### Debugging the Windows 10 Handler
1. Update the registry to point to your debug build:
```
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\CLSID\{<NewPlus-CLSID>}]
@="PowerToys NewPlus Extension"
[HKEY_CLASSES_ROOT\CLSID\{<NewPlus-CLSID>}\InprocServer32]
@="x:\GitHub\PowerToys\x64\Debug\PowerToys.NewPlusExt.win10.dll"
"ThreadingModel"="Apartment"
[HKEY_CURRENT_USER\Software\Classes\Directory\Background\shellex\ContextMenuHandlers\NewPlus]
@="{<NewPlus-CLSID>}"
```
2. Restart Explorer:
```
taskkill /f /im explorer.exe && start explorer.exe
```
3. Attach the debugger to explorer.exe
4. Add breakpoints in the NewPlus code
5. Right-click in File Explorer to trigger the context menu handler
### Debugging the Windows 11 Handler
Debugging the Windows 11 handler requires signing the MSIX package:
1. Build PowerToys to get the MSIX packages
2. **Create certificate** (if you don't already have one):
```powershell
New-SelfSignedCertificate -Subject "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" `
-KeyUsage DigitalSignature `
-Type CodeSigningCert `
-FriendlyName "PowerToys SelfCodeSigning" `
-CertStoreLocation "Cert:\CurrentUser\My"
```
3. **Get the certificate thumbprint**:
```powershell
$cert = Get-ChildItem -Path Cert:\CurrentUser\My | Where-Object { $_.FriendlyName -like "*PowerToys*" }
$cert.Thumbprint
```
4. **Install the certificate in the Trusted Root** (requires admin Terminal):
```powershell
Export-Certificate -Cert $cert -FilePath "$env:TEMP\PowerToysCodeSigning.cer"
Import-Certificate -FilePath "$env:TEMP\PowerToysCodeSigning.cer" -CertStoreLocation Cert:\LocalMachine\Root
```
Alternatively, you can manually install the certificate using the Certificate Import Wizard:
![wizard 1](../images/newplus/wizard1.png)
![wizard 2](../images/newplus/wizard2.png)
![wizard 3](../images/newplus/wizard3.png)
![wizard 4](../images/newplus/wizard4.png)
5. Sign the MSIX package:
```powershell
SignTool sign /fd SHA256 /sha1 <THUMBPRINT> "x:\GitHub\PowerToys\x64\Debug\WinUI3Apps\NewPlusPackage.msix"
```
Note: SignTool might not be in your PATH, so you may need to specify the full path, e.g.:
```powershell
& "C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\signtool.exe" sign /fd SHA256 /sha1 <THUMBPRINT> "x:\GitHub\PowerToys\x64\Debug\WinUI3Apps\NewPlusPackage.msix"
```
6. Check if the NewPlus package is already installed and remove it if necessary:
```powershell
Get-AppxPackage -Name Microsoft.PowerToys.NewPlusContextMenu
Remove-AppxPackage Microsoft.PowerToys.NewPlusContextMenu_<VERSION>_neutral__8wekyb3d8bbwe
```
7. Install the new signed MSIX package (optional if launching PowerToys settings first):
```powershell
Add-AppxPackage -Path "x:\GitHub\PowerToys\x64\Debug\WinUI3Apps\NewPlusPackage.msix" -ExternalLocation "x:\GitHub\PowerToys\x64\Debug\WinUI3Apps"
```
Note: If you prefer, you can simply launch PowerToys settings and enable the NewPlus module, which will install the MSIX package for you.
8. Restart Explorer to ensure the new context menu handler is loaded:
```powershell
taskkill /f /im explorer.exe && start explorer.exe
```
9. Run Visual Studio as administrator (optional)
10. Set breakpoints in the code (e.g., in [shell_context_menu.cpp#L45](/src/modules/NewPlus/NewShellExtensionContextMenu/shell_context_menu.cpp#L45))
11. Right-click in File Explorer and attach the debugger to the `DllHost.exe` process (with NewPlus title) that loads when the context menu is invoked
![alt text](../images/newplus/debug.png)
12. Right-click again (quickly) after attaching the debugger to trigger the breakpoint
Note: The DllHost process loads the DLL only when the context menu is triggered and unloads after, making debugging challenging. For easier development, consider using logging or message boxes instead of breakpoints.
## Common Issues
- If the Windows 11 context menu entry doesn't appear, it may be due to:
- The package not being properly registered
- Explorer not being restarted after registration
- A signature issue with the MSIX package
- For development and testing, using the Windows 10 handler can be easier since it doesn't require signing.

View File

@@ -1,5 +1,14 @@
# PowerToys Peek
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/peek)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AProduct-Peek)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3AProduct-Peek)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3AProduct-Peek)
> Documentation is currently under construction
## Dev file previewer

View File

@@ -1,23 +1,108 @@
#### [`dllmain.cpp`](/src/modules/powerrename/dll/dllmain.cpp)
TODO
# PowerRename
#### [`PowerRenameExt.cpp`](/src/modules/powerrename/dll/PowerRenameExt.cpp)
TODO
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/powerrename)
#### [`Helpers.cpp`](/src/modules/powerrename/lib/Helpers.cpp)
TODO
## Quick Links
#### [`PowerRenameItem.cpp`](/src/modules/powerrename/lib/PowerRenameItem.cpp)
TODO
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AProduct-PowerRename)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3AProduct-PowerRename)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3AProduct-PowerRename)
#### [`PowerRenameManager.cpp`](/src/modules/powerrename/lib/PowerRenameManager.cpp)
TODO
PowerRename is a Windows shell extension that enables batch renaming of files using search and replace or regular expressions.
#### [`PowerRenameRegEx.cpp`](/src/modules/powerrename/lib/PowerRenameRegEx.cpp)
TODO
## Overview
#### [`Settings.cpp`](/src/modules/powerrename/lib/Settings.cpp)
TODO
PowerRename provides a powerful and flexible way to rename files in File Explorer. It is accessible through the Windows context menu and allows users to:
- Preview changes before applying them
- Use search and replace with regular expressions
- Filter items by type (files or folders)
- Apply case-sensitive or case-insensitive matching
- Save and reuse recent search/replace patterns
#### [`trace.cpp`](/src/modules/powerrename/lib/trace.cpp)
TODO
## Architecture
PowerRename consists of multiple components:
- Shell Extension DLL (context menu integration)
- WinUI 3 UI application
- Core renaming library
### Technology Stack
- C++/WinRT
- WinUI 3
- COM for shell integration
## Context Menu Integration
PowerRename integrates with the Windows context menu following the [PowerToys Context Menu Handlers](../common/context-menus.md) pattern. It uses a dual registration approach to ensure compatibility with both Windows 10 and Windows 11.
### Registration Process
The context menu registration entry point is in `PowerRenameExt/dllmain.cpp::enable`, which registers:
- A traditional shell extension for Windows 10
- A sparse MSIX package for Windows 11 context menus
For more details on the implementation approach, see the [Dual Registration section](../common/context-menus.md#1-dual-registration-eg-imageresizer-powerrename) in the context menu documentation.
## Code Components
### [`dllmain.cpp`](/src/modules/powerrename/dll/dllmain.cpp)
Contains the DLL entry point and module activation/deactivation code. The key function `RunPowerRename` is called when the context menu option is invoked, which launches the PowerRenameUI.
### [`PowerRenameExt.cpp`](/src/modules/powerrename/dll/PowerRenameExt.cpp)
Implements the shell extension COM interfaces required for context menu integration, including:
- `IShellExtInit` for initialization
- `IContextMenu` for traditional context menu support
- `IExplorerCommand` for Windows 11 context menu support
### [`Helpers.cpp`](/src/modules/powerrename/lib/Helpers.cpp)
Utility functions used throughout the PowerRename module, including file system operations and string manipulation.
### [`PowerRenameItem.cpp`](/src/modules/powerrename/lib/PowerRenameItem.cpp)
Represents a single item (file or folder) to be renamed. Tracks original and new names and maintains state.
### [`PowerRenameManager.cpp`](/src/modules/powerrename/lib/PowerRenameManager.cpp)
Manages the collection of items to be renamed and coordinates the rename operation.
### [`PowerRenameRegEx.cpp`](/src/modules/powerrename/lib/PowerRenameRegEx.cpp)
Implements the regular expression search and replace functionality used for renaming.
### [`Settings.cpp`](/src/modules/powerrename/lib/Settings.cpp)
Manages user preferences and settings for the PowerRename module.
### [`trace.cpp`](/src/modules/powerrename/lib/trace.cpp)
Implements telemetry and logging functionality.
## UI Implementation
PowerRename uses WinUI 3 for its user interface. The UI allows users to:
- Enter search and replace patterns
- Preview rename results in real-time
- Access previous search/replace patterns via MRU (Most Recently Used) lists
- Configure various options
### Key UI Components
- Search/Replace input fields with x:Bind to `SearchMRU`/`ReplaceMRU` collections
- Preview list showing original and new filenames
- Settings panel for configuring rename options
- Event handling for `SearchReplaceChanged` to update the preview in real-time
## Debugging
### Debugging the Context Menu
See the [Debugging Context Menu Handlers](../common/context-menus.md#debugging-context-menu-handlers) section for general guidance on debugging PowerToys context menu extensions.
### Debugging the UI
To debug the PowerRename UI:
1. Add file paths manually in `\src\modules\powerrename\PowerRenameUILib\PowerRenameXAML\App.xaml.cpp`
2. Set the PowerRenameUI project as the startup project
3. Run in debug mode to test with the manually specified files
### Common Issues
- Context menu not appearing: Ensure the extension is properly registered and Explorer has been restarted
- UI not launching: Check Event Viewer for errors related to WinUI 3 application activation
- Rename operations failing: Verify file permissions and check for locked files

View File

@@ -0,0 +1,119 @@
# Quick Accent
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/quick-accent)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Quick%20Accent%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-Quick%20Accent%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-Quick+Accent%22)
## Overview
Quick Accent (formerly known as Power Accent) is a PowerToys module that allows users to quickly insert accented characters by holding a key and pressing an activation key (like the Space key or arrow keys). For example, holding 'a' might display options like 'à', 'á', 'â', etc. This tool enhances productivity by streamlining the input of special characters without the need to memorize keyboard shortcuts.
## Architecture
The Quick Accent module consists of four main components:
```
poweraccent/
├── PowerAccent.Core/ # Core component containing Language Sets
├── PowerAccent.UI/ # The character selector UI
├── PowerAccentKeyboardService/ # Keyboard Hook
└── PowerAccentModuleInterface/ # DLL interface
```
### Module Interface (PowerAccentModuleInterface)
The Module Interface, implemented in `PowerAccentModuleInterface/dllmain.cpp`, is responsible for:
- Handling communication between PowerToys Runner and the PowerAccent process
- Managing module lifecycle (enable/disable/settings)
- Launching and terminating the PowerToys.PowerAccent.exe process
### Core Logic (PowerAccent.Core)
The Core component contains:
- Main accent character logic
- Keyboard input detection
- Character mappings for different languages
- Management of language sets and special characters (currency, math symbols, etc.)
- Usage statistics for frequently used characters
### UI Layer (PowerAccent.UI)
The UI component is responsible for:
- Displaying the toolbar with accent options
- Handling user selection of accented characters
- Managing the visual positioning of the toolbar
### Keyboard Service (PowerAccentKeyboardService)
This component:
- Implements keyboard hooks to detect key presses
- Manages the trigger mechanism for displaying the accent toolbar
- Handles keyboard input processing
## Implementation Details
### Activation Mechanism
The Quick Accent is activated when:
1. A user presses and holds a character key (e.g., 'a')
2. User presses the trigger key
3. After a brief delay (around 300ms per setting), the accent toolbar appears
4. The user can select an accented variant using the trigger key
5. Upon releasing the keys, the selected accented character is inserted
### Character Sets
The module includes multiple language-specific character sets and special character sets:
- Various language sets for different alphabets and writing systems
- Special character sets (currency symbols, mathematical notations, etc.)
- These sets are defined in the core component and can be extended
### Known Behaviors
- The module has a specific timing mechanism for activation that users have become accustomed to. Initially, this was considered a bug (where the toolbar would still appear even after quickly tapping and releasing keys), but it has been maintained as expected behavior since users rely on it.
- Multiple rapid key presses can trigger multiple background tasks.
## Future Considerations
- Potential refinements to the activation timing mechanism
- Additional language and special character sets
- Improved UI positioning in different application contexts
## Debugging
To debug the Quick Accent module via **runner** approach, follow these steps:
0. Get familiar with the overall [Debugging Process](../development/debugging.md) for PowerToys.
1. **Build** the entire PowerToys solution in Visual Studio
2. Navigate to the **PowerAccent** folder in Solution Explorer
3. Open the file you want to debug and set **breakpoints** at the relevant locations
4. Find the **runner** project in the root of the solution
5. Right-click on the **runner** project and select "*Set as Startup Project*"
6. Start debugging by pressing `F5` or clicking the "*Start*" button
7. When the PowerToys Runner launches, **enable** the Quick Accent module in the UI
8. Use the Visual Studio Debug menu or press `Ctrl+Alt+P` to open "*Reattach to Process*"
9. Find and select "**PowerToys.PowerAccent.exe**" in the process list
10. Trigger the action in Quick Accent that should hit your breakpoint
11. Verify that the debugger breaks at your breakpoint and you can inspect variables and step through code
This process allows you to debug the Quick Accent module while it's running as part of the full PowerToys application.
### Alternative Debugging Approach
To directly debug the Quick Accent UI component:
0. Get familiar with the overall [Debugging Process](../development/debugging.md) for PowerToys.
1. **Build** the entire PowerToys solution in Visual Studio
2. Navigate to the **PowerAccent** folder in Solution Explorer
3. Open the file you want to debug and set **breakpoints** at the relevant locations
4. Right-click on the **PowerAccent.UI** project and select "*Set as Startup Project*"
5. Start debugging by pressing `F5` or clicking the "*Start*" button
6. Verify that the debugger breaks at your breakpoint and you can inspect variables and step through code
**Known issue**: You may encounter approximately 78 errors during the start of debugging.<br>
**Solution**: If you encounter errors, right-click on the **PowerAccent** folder in Solution Explorer and select "*Rebuild*". After rebuilding, start debugging again.

View File

@@ -0,0 +1,43 @@
# PowerToys Modules
This section contains documentation for individual PowerToys modules, including their architecture, implementation details, and debugging tools.
## Available Modules
| Module | Description |
|--------|-------------|
| [Advanced Paste](advancedpaste.md) | Tool for enhanced clipboard pasting with formatting options |
| [Always on Top](alwaysontop.md) | Tool for pinning windows to stay on top of other windows |
| [Awake](awake.md) | Tool to keep your computer awake without modifying power settings |
| [Color Picker](colorpicker.md) | Tool for selecting and managing colors from the screen |
| [Command Not Found](commandnotfound.md) | Tool suggesting package installations for missing commands |
| [Crop and Lock](cropandlock.md) | Tool for cropping application windows into smaller windows or thumbnails |
| [Environment Variables](environmentvariables.md) | Tool for managing user and system environment variables |
| [FancyZones](fancyzones.md) ([debugging tools](fancyzones-tools.md)) | Window manager utility for custom window layouts |
| [File Explorer add-ons](fileexploreraddons.md) | Extensions for enhancing Windows File Explorer functionality |
| [File Locksmith](filelocksmith.md) | Tool for finding processes that lock files |
| [Hosts File Editor](hostsfileeditor.md) | Tool for managing the system hosts file |
| [Image Resizer](imageresizer.md) | Tool for quickly resizing images within File Explorer |
| [Keyboard Manager](keyboardmanager/README.md) | Tool for remapping keys and keyboard shortcuts |
| [Mouse Utilities](mouseutils/readme.md) | Collection of tools to enhance mouse and cursor functionality |
| [Mouse Without Borders](mousewithoutborders.md) | Tool for controlling multiple computers with a single mouse and keyboard |
| [NewPlus](newplus.md) | Context menu extension for creating new files in File Explorer |
| [Peek](peek/readme.md) | File preview utility for quick file content viewing |
| [Power Rename](powerrename.md) | Bulk file renaming tool with search and replace functionality |
| [PowerToys Run (deprecation soon)](launcher/readme.md) | Quick application launcher and search utility |
| [Quick Accent](quickaccent.md) | Tool for quickly inserting accented characters and special symbols |
| [Registry Preview](registrypreview.md) | Tool for visualizing and editing Registry files |
| [Screen Ruler](screenruler.md) | Tool for measuring pixel distances and color boundaries on screen |
| [Shortcut Guide](shortcut_guide.md) | Tool for displaying Windows keyboard shortcuts when holding the Windows key |
| [Text Extractor](textextractor.md) | Tool for extracting text from images and screenshots |
| [Workspaces](workspaces.md) | Tool for saving and restoring window layouts for different projects |
| [ZoomIt](zoomit.md) | Screen zoom and annotation tool |
## Adding New Module Documentation
When adding documentation for a new module:
1. Create a dedicated markdown file for the module (e.g., `modulename.md`)
2. If the module has specialized debugging tools, consider creating a separate tools document (e.g., `modulename-tools.md`)
3. Update this index with links to the new documentation
4. Follow the existing documentation structure for consistency

View File

@@ -0,0 +1,85 @@
# Registry Preview Module
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/registry-preview)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Registry%20Preview%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-Registry%20Preview%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-Registry+Preview%22)
[CheckList](https://github.com/microsoft/PowerToys/blob/releaseChecklist/doc/releases/tests-checklist-template.md?plain=1#L641)
## Overview
Registry Preview simplifies the process of visualizing and editing complex Windows Registry files. It provides a powerful interface to preview, edit, and write changes to the Windows Registry. The module leverages the [Monaco Editor](../common/monaco-editor.md) to provide features like syntax highlighting and line numbering for registry files.
## Technical Architecture
Registry Preview is built using WinUI 3 with the [Monaco Editor](../common/monaco-editor.md) embedded for text editing capabilities. Monaco was originally designed for web environments but has been integrated into this desktop application to leverage its powerful editing features.
The module consists of several key components:
1. **Main Windows Interface** - Handles the UI interactions, window messaging, and resource loading
2. **Monaco Editor Integration** - Embeds the Monaco web-based editor into WinUI 3 (see [Monaco Editor documentation](../common/monaco-editor.md) for details)
3. **Registry Parser** - Parses registry files and builds a tree structure for visualization
4. **Editor Control** - Manages the editing capabilities and syntax highlighting
## Code Structure
The Registry Preview module is organized into the following projects:
- **RegistryPreview** - Main window implementation, including Windows message handling, resource loading, and service injection
- **RegistryPreviewUILib** - UI implementation details and backend logic
- **RegistryPreviewExt** - Project configuration and setup
- **RegistryPreview.FuzzTests** - Fuzzing tests for the module
Key files and components:
1. **MonacoEditorControl** - Handles the embedding of [Monaco](../common/monaco-editor.md) into WinUI 3 and sets up the WebView container
2. **MainWindow** - Manages all event handling in one place
3. **Utilities** - Contains shared helper methods and utility classes
## Main Functions
- **MonacoEditorControl**: Controls editing in Monaco
- **GetRuntimeMonacoDirectory**: Gets the current directory path
- **OpenRegistryFile**: Opens and processes a registry file (first-time open)
- **RefreshRegistryFile**: Re-opens and processes an already opened file
- **ParseRegistryFile**: Parses text from the editor
- **AddTextToTree**: Creates TreeView nodes from registry keys
- **ShowMessageBox**: Wrapper method for displaying message boxes
## Debugging Registry Preview
### Setup Debugging Environment
1. Set the PowerToys Runner as the parent process
2. Set the RegistryPreviewUILib project as the child process for debugging
3. Use the PowerToys Development Utility tool to configure debugging
### Debugging Tips
1. The main application logic is in the RegistryPreviewUILib project
2. Monaco-related issues may require debugging the WebView component (see [Monaco Editor documentation](../common/monaco-editor.md) for details)
3. For parsing issues, add breakpoints in the ParseRegistryFile method
4. UI issues are typically handled in the main RegistryPreview project
## UI Automation
Currently, Registry Preview does not have UI automation tests implemented. This is a potential area for future development.
## Recent Updates
Registry Preview has received community contributions, including:
- UI improvements
- New buttons and functionality
- Data preview enhancements
- Save button improvements
## Future Considerations
- Adding UI automation tests
- Further [Monaco editor](../common/monaco-editor.md) updates
- Enhanced registry parsing capabilities
- Improved visualization options

View File

@@ -0,0 +1,68 @@
# Screen Ruler
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/screen-ruler)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Screen%20Ruler%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-Screen%20Ruler%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-Screen+Ruler%22)
## Overview
Screen Ruler (project name: MeasureTool or Measure 2) is a PowerToys module that allows users to measure pixel distances and detect color boundaries on the screen. The tool renders an overlay UI using DirectX and provides several measurement utilities.
## Features
- **Bounce Utility**: Measure a rectangular zone by dragging with a left click
- **Spacing Tool**: Measure the length of a line with the same color with the same pixel value both horizontally and vertically
- **Horizontal Spacing**: Measure the line with the same color in the horizontal direction
- **Vertical Spacing**: Measure the line with the same color in the vertical direction
## Architecture & Implementation
The Screen Ruler module consists of several components:
### MeasureToolModuleInterface
- **Dllmain.cpp**: Provides functionality to start and stop the Measure Tool process based on hotkey events, manage settings, and handle events.
### MeasureToolUI
- **App.xaml.cs**: Main entrance of the app. Initializes MeasureToolCore and activates a new main window.
- **MainWindow.xaml.cs**: Sets properties and behaviors for the window, and handles user click interactions.
- **NativeMethods.cs**: Interacts with the Windows API to manipulate window properties, such as positioning and sizing.
- **Settings.cs**: Gets the default measure style from settings.
### PowerToys.MeasureToolCore
- **PowerToys.MeasureToolCore**: Handles initialization, state management, and starts the measure tool and bounds tool.
- **BGRATextureView.h**: Manages and interacts with BGRA textures in a Direct3D 11 context.
- **Measurement.cpp**: Defines a Measurement struct that represents a rectangular measurement area, including methods for converting and printing measurement details in various units.
- **Clipboard.cpp**: Copies measurement data to the clipboard.
- **D2DState.cpp**: Manages Direct2D rendering state and draws text boxes.
- **DxgiAPI.cpp**: Creates and manages Direct3D and Direct2D devices.
- **EdgeDetection.cpp**: Detects edges in a BGRA texture.
- **OverlayUI.cpp**: Creates and manages overlay windows for tools like MeasureTool and BoundsTool.
- **BoundsToolOverlayUI.cpp**: UI implementation for bounds feature. Handles mouse and touch events to draw measurement rectangles on the screen and display their pixels.
- **MeasureToolOverlayUI.cpp**: UI implementation for measure feature. Draws measurement lines on the screen and displays their pixels.
- **ScreenCapturing.cpp**: Continuously captures the screen, detects edges, and updates the measurement state for real-time drawing of measurement lines.
- **PerGlyphOpacityTextRender.cpp**: Renders text with varying opacity on a Direct2D render target.
## Building & Debugging
### Building
1. Open PowerToys.sln in Visual Studio
2. In the Solutions Configuration drop-down menu, select Release or Debug
3. From the Build menu, choose Build Solution
4. The executable app for Screen Ruler is named PowerToys.MeasureToolUI.exe
### Debugging
1. Right-click the project MeasureToolUI and click 'Set as Startup Project'
2. Right-click the project MeasureToolUI and click 'Debug'
## Known Issues
There are several open bugs for the Screen Ruler module, most of which are related to crashing issues. These can be found in the [PowerToys issues list](https://github.com/microsoft/PowerToys/issues?q=is%3Aissue%20state%3Aopen%20Screen%20ruler%20type%3ABug).

View File

@@ -1,17 +1,91 @@
# Shortcut Guide
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/shortcut-guide)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Shortcut%20Guide%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-Shortcut%20Guide%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-Shortcut+Guide%22+)
## Overview
Shortcut Guide is a PowerToy that displays an overlay of available keyboard shortcuts when the Windows key is pressed and held. It provides a visual reference for Windows key combinations, helping users discover and utilize built-in Windows shortcuts.
## Usage
- Press and hold the Windows key to display the overlay of available shortcuts
- Press the hotkey again to dismiss the overlay
- The overlay displays Windows shortcuts with their corresponding actions
## Build and Debug Instructions
### Build
1. Open PowerToys.sln in Visual Studio
2. Select Release or Debug in the Solutions Configuration drop-down menu
3. From the Build menu, choose Build Solution
4. The executable is named PowerToys.ShortcutGuide.exe
### Debug
1. Right-click the ShortcutGuide project and select 'Set as Startup Project'
2. Right-click the project again and select 'Debug'
## Code Structure
![Diagram](../images/shortcutguide/diagram.png)
### Core Files
#### [`dllmain.cpp`](/src/modules/shortcut_guide/dllmain.cpp)
Contains DLL boilerplate code.
Contains DLL boilerplate code. Implements the PowertoyModuleIface, including enable/disable functionality and GPO policy handling. Captures hotkey events and starts the PowerToys.ShortcutGuide.exe process to display the shortcut guide window.
#### [`shortcut_guide.cpp`](/src/modules/shortcut_guide/shortcut_guide.cpp)
Contains the module interface code. It initializes the settings values and the keyboard event listener.
Contains the module interface code. It initializes the settings values and the keyboard event listener. Defines the OverlayWindow class, which manages the overall logic and event handling for the PowerToys Shortcut Guide.
#### [`overlay_window.cpp`](/src/modules/shortcut_guide/overlay_window.cpp)
Contains the code for loading the SVGs, creating and rendering of the overlay window.
Contains the code for loading the SVGs, creating and rendering of the overlay window. Manages and displays overlay windows with SVG graphics through two main classes:
- D2DOverlaySVG: Handles loading, resizing, and manipulation of SVG graphics
- D2DOverlayWindow: Manages the display and behavior of the overlay window
#### [`keyboard_state.cpp`](/src/modules/shortcut_guide/keyboard_state.cpp)
Contains helper methods for checking the current state of the keyboard.
#### [`target_state.cpp`](/src/modules/shortcut_guide/target_state.cpp)
State machine that handles the keyboard events. Its responsible for deciding when to show the overlay, when to suppress the Start menu (if the overlay is displayed long enough), etc.
State machine that handles the keyboard events. It's responsible for deciding when to show the overlay, when to suppress the Start menu (if the overlay is displayed long enough), etc. Handles state transitions and synchronization to ensure the overlay is shown or hidden appropriately based on user interactions.
#### [`trace.cpp`](/src/modules/shortcut_guide/trace.cpp)
Contains code for telemetry.
### Supporting Files
#### [`animation.cpp`](/src/modules/shortcut_guide/animation.cpp)
Handles the timing and interpolation of animations. Calculates the current value of an animation based on elapsed time and a specified easing function.
#### [`d2d_svg.cpp`](/src/modules/shortcut_guide/d2d_svg.cpp)
Provides functionality for loading, resizing, recoloring, rendering, and manipulating SVG images using Direct2D.
#### [`d2d_text.cpp`](/src/modules/shortcut_guide/d2d_text.cpp)
Handles creation, resizing, alignment, and rendering of text using Direct2D and DirectWrite.
#### [`d2d_window.cpp`](/src/modules/shortcut_guide/d2d_window.cpp)
Manages a window using Direct2D and Direct3D for rendering. Handles window creation, resizing, rendering, and destruction.
#### [`native_event_waiter.cpp`](/src/modules/shortcut_guide/native_event_waiter.cpp)
Waits for a named event and executes a specified action when the event is triggered. Uses a separate thread to handle event waiting and action execution.
#### [`tasklist_positions.cpp`](/src/modules/shortcut_guide/tasklist_positions.cpp)
Handles retrieving and updating the positions and information of taskbar buttons in Windows.
#### [`main.cpp`](/src/modules/shortcut_guide/main.cpp)
The entry point for the PowerToys Shortcut Guide application. Handles initialization, ensures single instance execution, manages parent process termination, creates and displays the overlay window, and runs the main event loop.
## Features and Limitations
- The overlay displays Windows shortcuts (Windows key combinations)
- The module supports localization, but only for the Windows controls on the left side of the overlay
- It's currently rated as a P3 (lower priority) module
## Future Development
A community-contributed version 2 is in development that will support:
- Application-specific shortcuts based on the active application
- Additional shortcuts beyond Windows key combinations
- PowerToys shortcuts

View File

@@ -0,0 +1,34 @@
# Text Extractor
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/text-extractor)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3A%22Product-Text%20Extractor%22)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3A%22Product-Text%20Extractor%22)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3A%22Product-Text+Extractor%22)
## Overview
Text Extractor is a PowerToys utility that enables users to extract and copy text from anywhere on the screen, including inside images and videos. The module uses Optical Character Recognition (OCR) technology to recognize text in visual content. This module is based on Joe Finney's Text Grab.
## How it works
Text Extractor captures the screen content and uses OCR to identify and extract text from the selected area. Users can select a region of the screen, and Text Extractor will convert any visible text in that region into copyable text.
## Architecture
### Components
- **EventMonitor**: Handles the `ShowPowerOCRSharedEvent` which triggers the OCR functionality
- **OCROverlay**: The main UI component that provides:
- Language selection for OCR processing
- Canvas for selecting the screen area to extract text from
- **Screen Capture**: Uses `CopyFromScreen` to capture the screen content as the overlay background image
### Activation Methods
- **Global Shortcut**: Activates Text Extractor through a keyboard shortcut
- **LaunchOCROverlayOnEveryScreen**: Functionality to display the OCR overlay across multiple monitors
## Technical Implementation
Text Extractor is implemented using Windows Presentation Foundation (WPF) technology, which provides the UI framework for the selection canvas and other interface elements.
## User Experience
When activated, Text Extractor displays an overlay on the screen that allows users to select an area containing text. Once selected, the OCR engine processes the image and extracts any text found, which can then be copied to the clipboard.

View File

@@ -0,0 +1,34 @@
# Workspaces
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/workspaces)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AProduct-Workspaces)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AIssue-Bug%20label%3AProduct-Workspaces)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3AProduct-Workspaces)
## Overview
Workspaces is a PowerToys module that allows users to save and restore window layouts for different projects or workflows.
## Links
- [Source code folder](https://github.com/microsoft/PowerToys/tree/main/src/modules/Workspaces)
- [Issue tracker](https://github.com/microsoft/PowerToys/issues?q=is%3Aissue+label%3AWorkspaces)
## Implementation Details
TODO: Add implementation details
## Debugging
TODO: Add debugging information
## Settings
TODO: Add settings documentation
## Future Improvements
TODO: Add potential future improvements

View File

@@ -0,0 +1,194 @@
# ZoomIt Module
[Public overview - Microsoft Learn](https://learn.microsoft.com/en-us/windows/powertoys/zoomit)
## Quick Links
[All Issues](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AProduct-ZoomIt)<br>
[Bugs](https://github.com/microsoft/PowerToys/issues?q=is%3Aopen%20label%3AProduct-ZoomIt%20label%3AIssue-Bug%20)<br>
[Pull Requests](https://github.com/microsoft/PowerToys/pulls?q=is%3Apr+is%3Aopen+label%3AProduct-ZoomIt)
## Overview
ZoomIt is a screen zoom and annotation tool originally from Microsoft's Sysinternals suite. It allows users to:
- Zoom in on specific areas of the screen
- Draw and annotate on the screen while zoomed in
- Use a timer for presentations or breaks
- Pan and move while zoomed in
- Record screen activity with audio
ZoomIt runs in the background and is activated via customizable hotkeys.
## Special Integration Considerations
Unlike other PowerToys modules, ZoomIt has some unique integration aspects:
1. **Registry-based Settings**: ZoomIt uses registry settings instead of JSON files (which is the standard for other PowerToys modules). This was required to maintain compatibility with the standalone Sysinternals version.
2. **Dual Source of Truth**: The PowerToys repository serves as the source of truth for both the PowerToys version and the standalone Sysinternals version, with build flags to differentiate between them.
3. **Settings Integration**: A special WinRT/C++ interop library was developed to bridge between PowerToys' JSON-based settings system and ZoomIt's registry-based settings.
## Technical Architecture
The ZoomIt module consists of the following components:
1. **ZoomIt Executable** (`PowerToys.ZoomIt.exe`): The main ZoomIt application that provides the zooming and annotation functionality.
2. **Module Interface** (`PowerToys.ZoomItModuleInterface.dll`): Implements the PowerToys module interface to integrate with the PowerToys runner.
3. **Settings Interop** (`ZoomItSettingsInterop`): A WinRT/C++ interop library that enables communication between PowerToys settings and ZoomIt's registry settings.
![key functions](../images/zoomit/functions.png)
### Directory Structure
```
src/
├── modules/
│ └── ZoomIt/
│ ├── ZoomIt/ # Main ZoomIt application code
│ ├── ZoomItModuleInterface/ # PowerToys module interface implementation
│ └── ZoomItSettingsInterop/ # WinRT/C++ interop for settings
├── settings-ui/
│ └── Settings.UI/
│ ├── SettingsXAML/
│ │ └── Views/
│ │ └── ZoomItPage.xaml # ZoomIt settings page UI
│ └── ViewModels/
│ └── ZoomItViewModel.cs # ZoomIt settings view model
└── common/
└── sysinternals/ # Common code from Sysinternals
```
## Settings Management
ZoomIt's settings are stored in the Windows registry instead of JSON files to maintain compatibility with the standalone version. The settings include:
- Hotkey combinations for different modes (zoom, draw, etc.)
- Drawing options (colors, line thickness, etc.)
- Font settings for text annotations
- Microphone selection for recording
- Custom file paths for demo mode and break backgrounds
The `ZoomItSettingsInterop` library handles:
1. Loading settings from registry and converting to JSON for PowerToys settings UI
2. Saving changes from the settings UI back to the registry
3. Notifying the ZoomIt application when settings change
![interop](../images/zoomit/interop.png)
## Integration Steps
The integration of ZoomIt into PowerToys involved these key steps:
1. **Code Migration**:
- Moving code from the Sysinternals ZoomIt repository to `src/modules/ZoomIt/ZoomIt`
- Adding required common libraries to `src/common/sysinternals`
- Sanitizing code for open source (removing private APIs, undocumented details, etc.)
- Ensuring no private APIs (validated through APIScan)
- Removing references to undocumented implementation details, constants, and names
- Standardizing dependencies with other PowerToys utilities
2. **Module Interface Implementation**:
- Creating the PowerToys module interface
- Adding process management (start/terminate)
- Implementing event-based communication for settings updates
- Adding named events for communication between PowerToys and ZoomIt
3. **Settings Integration**:
- Extracting ZoomIt settings code to a shareable component
- Creating a WinRT/C++ interop library for registry-JSON conversion
- Implementing all settings UI controls in PowerToys settings
- Building `ZoomItSettingsInterop` as a bridge between registry and JSON settings
4. **PowerToys Integration**:
- Adding ZoomIt to the PowerToys runner
- Adding GPO rules for ZoomIt
- Implementing telemetry and logging
- Creating OOBE (out-of-box experience) page with animated tutorial
- Adding ZoomIt to process termination list for proper cleanup
- Adding telemetry events documentation
5. **UI/UX Adjustments**:
- Redirecting ZoomIt's settings UI to PowerToys settings
- Handling hotkey conflicts with warning notifications
- Modifying tray icon behavior
- Removing original ZoomIt options menu entries
- Adding Sysinternals attribution on the settings page
6. **Build System Updates**:
- Adding ZoomIt to the PowerToys solution
- Implementing build flags for standalone vs. PowerToys versions
- Adding signing for new binaries
- Fixing analyzer errors and code quality issues
## Debug Instructions
1. Build the entire PowerToys solution at least once.
2. Set `runner` as the startup project and start debugging.
3. Once the PowerToys Settings app is running and ensure ZoomIt is activated.
4. Set `ZoomIt` as the startup project in Visual Studio.
5. Press `Ctrl + Alt + P` and attach ZoomIt to the process.
6. You should now be able to set breakpoints and step through the code.
## Special Implementation Details
### Font Selection
ZoomIt requires storing font information as a binary LOGFONT structure in the registry. This required special handling:
- Creating P/Invoke declarations for Windows font APIs
- Base64 encoding the binary data for transfer through JSON
- Using native Windows dialogs for font selection
### Hotkey Management
ZoomIt registers hotkeys through the Windows RegisterHotKey API. Special handling was needed to:
- Detect and notify about hotkey conflicts
- Update hotkeys when settings change
- Support modifier keys
### Process Communication
Communication between PowerToys and ZoomIt uses:
- Command-line arguments to pass PowerToys process ID
- Named events for signaling settings changes and exit requests
- Windows messages for internal ZoomIt state management
## Implementation Challenges
Several challenges were encountered during ZoomIt integration:
1. **First-Run Behavior**:
- Font loading crashed when no ZoomIt data existed in registry
- Hotkeys weren't registered on first run with no existing data
- Implemented safeguards to handle missing registry data
2. **Settings Synchronization**:
- Modifier keys for shortcuts weren't correctly updated when settings changed
- Implemented proper event notification for settings changes
- Added hotkey conflict detection and warnings
3. **File Interaction**:
- ZoomIt file pickers changed the working directory of the Settings project
- Fixed to maintain proper directory context
4. **Drawing Issues**:
- Color settings lacking opacity caused drawing functionality to fail
- Removed internal state settings that weren't truly editable
5. **Dual-Build Support**:
- Added build flags to support both PowerToys and standalone Sysinternals versions
- Implemented different executable properties based on build target
## Source Code Management
The PowerToys repository serves as the source of truth for both PowerToys and Sysinternals standalone versions of ZoomIt. Key repositories involved:
- Utility repo: `https://dev.azure.com/sysinternals/Tools/_git/ZoomIt`
- Common library repo: `https://dev.azure.com/sysinternals/Tools/_git/Common`
The integration process can be tracked through [PR #35880](https://github.com/microsoft/PowerToys/pull/35880) which contains the complete history of changes required to properly integrate ZoomIt.