From 8fb18bd6c2fbf81b22cab252ab7764ca65119dc7 Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Fri, 7 Aug 2026 22:25:45 -0700 Subject: [PATCH 1/2] Batch high-confidence repo-assist improvements Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 83256e33-0073-41df-8635-10e4fba2ec65 --- .github/workflows/build.yml | 322 +- .github/workflows/ci.yml | 44 + README.md | 408 +-- WindowsEdgeLight.Tests/AppSettingsTests.cs | 137 + .../WindowsEdgeLight.Tests.csproj | 24 + WindowsEdgeLight.sln | 54 +- WindowsEdgeLight/AppSettings.cs | 265 +- WindowsEdgeLight/AssemblyInfo.cs | 23 +- WindowsEdgeLight/ControlWindow.xaml.cs | 232 +- WindowsEdgeLight/MainWindow.xaml.cs | 2913 +++++++++-------- WindowsEdgeLight/SettingsWindow.xaml.cs | 306 +- 11 files changed, 2504 insertions(+), 2224 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 WindowsEdgeLight.Tests/AppSettingsTests.cs create mode 100644 WindowsEdgeLight.Tests/WindowsEdgeLight.Tests.csproj diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 11cab2d..360ea58 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,157 +1,165 @@ -name: Build Release - -on: - push: - tags: - - 'v*' - workflow_dispatch: - -permissions: - contents: write - -jobs: - build: - runs-on: windows-latest - - steps: - - name: Checkout code - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: '10.0.x' - - - name: Restore dependencies - run: dotnet restore WindowsEdgeLight/WindowsEdgeLight.csproj - - - name: Install GitVersion - uses: gittools/actions/gitversion/setup@v4 - with: - versionSpec: '6.4.x' - - - name: GitVersion - uses: gittools/actions/gitversion/execute@v4 - id: gitversion - - - name: Set version environment variables - shell: pwsh - run: | - # Use GitVersion outputs for all versioning - $version = '${{ steps.gitversion.outputs.semVer }}' - $fullVersion = '${{ steps.gitversion.outputs.fullSemVer }}' - - # Assembly version must be 4-part (x.y.z.w) - $assemblyVersion = "${{ steps.gitversion.outputs.major }}.${{ steps.gitversion.outputs.minor }}.${{ steps.gitversion.outputs.patch }}.0" - - Write-Host "Using semantic version: $version" - Write-Host "Using full version: $fullVersion" - Write-Host "Using assembly version: $assemblyVersion" - - echo "VERSION=$version" >> $env:GITHUB_ENV - echo "FULLVERSION=$fullVersion" >> $env:GITHUB_ENV - echo "ASSEMBLY_VERSION=$assemblyVersion" >> $env:GITHUB_ENV - - - name: Build x64 - run: | - dotnet publish WindowsEdgeLight/WindowsEdgeLight.csproj ` - -c Release ` - -r win-x64 ` - /p:DebugType=None ` - /p:DebugSymbols=false ` - /p:Version=$env:VERSION ` - /p:AssemblyVersion=$env:ASSEMBLY_VERSION ` - /p:FileVersion=$env:ASSEMBLY_VERSION ` - /p:AssemblyInformationalVersion=$env:FULLVERSION ` - --self-contained - - - name: Build ARM64 - run: | - dotnet publish WindowsEdgeLight/WindowsEdgeLight.csproj ` - -c Release ` - -r win-arm64 ` - /p:DebugType=None ` - /p:DebugSymbols=false ` - /p:Version=$env:VERSION ` - /p:AssemblyVersion=$env:ASSEMBLY_VERSION ` - /p:FileVersion=$env:ASSEMBLY_VERSION ` - /p:AssemblyInformationalVersion=$env:FULLVERSION ` - --self-contained - - - name: Azure Login - uses: azure/login@v2 - with: - creds: '{"clientId":"${{ secrets.AZURE_CLIENT_ID }}","clientSecret":"${{ secrets.AZURE_CLIENT_SECRET }}","subscriptionId":"${{ secrets.AZURE_SUBSCRIPTION_ID }}","tenantId":"${{ secrets.AZURE_TENANT_ID }}"}' - - - name: Sign executables with Trusted Signing - uses: azure/trusted-signing-action@v1 - with: - azure-tenant-id: ${{ secrets.AZURE_TENANT_ID }} - azure-client-id: ${{ secrets.AZURE_CLIENT_ID }} - azure-client-secret: ${{ secrets.AZURE_CLIENT_SECRET }} - endpoint: https://wus2.codesigning.azure.net/ - signing-account-name: hanselman - certificate-profile-name: WindowsEdgeLight - files-folder: ${{ github.workspace }}\WindowsEdgeLight\bin\Release\net10.0-windows - files-folder-filter: exe - files-folder-recurse: true - file-digest: SHA256 - timestamp-rfc3161: http://timestamp.acs.microsoft.com - timestamp-digest: SHA256 - - - name: Prepare artifacts - shell: pwsh - run: | - New-Item -ItemType Directory -Path artifacts -Force - # Use VERSION environment variable (calculated via GitVersion) - $version = $env:VERSION - - # Create ZIP files with exe and README (so Updatum treats as portable app) - New-Item -ItemType Directory -Path "temp-x64" -Force - Copy-Item "WindowsEdgeLight/bin/Release/net10.0-windows/win-x64/publish/WindowsEdgeLight.exe" -Destination "temp-x64/" - Copy-Item "README.md" -Destination "temp-x64/" - Compress-Archive -Path "temp-x64/*" -DestinationPath "artifacts/WindowsEdgeLight-v$version-win-x64.zip" - - New-Item -ItemType Directory -Path "temp-arm64" -Force - Copy-Item "WindowsEdgeLight/bin/Release/net10.0-windows/win-arm64/publish/WindowsEdgeLight.exe" -Destination "temp-arm64/" - Copy-Item "README.md" -Destination "temp-arm64/" - Compress-Archive -Path "temp-arm64/*" -DestinationPath "artifacts/WindowsEdgeLight-v$version-win-arm64.zip" - - Remove-Item "temp-x64" -Recurse -Force - Remove-Item "temp-arm64" -Recurse -Force - - - name: Upload artifacts - uses: actions/upload-artifact@v4 - with: - name: WindowsEdgeLight-Release - path: artifacts/*.zip - - - name: Create Release - if: startsWith(github.ref, 'refs/tags/') - uses: softprops/action-gh-release@v1 - with: - files: artifacts/*.zip - generate_release_notes: true - body: | - ## Windows Edge Light ${{ github.ref_name }} - - ### 📦 Downloads - - | File | Platform | - |------|----------| - | `WindowsEdgeLight-${{ github.ref_name }}-win-x64.zip` | Intel/AMD 64-bit Windows | - | `WindowsEdgeLight-${{ github.ref_name }}-win-arm64.zip` | ARM64 Windows (Surface Pro X, etc.) | - - **Self-contained** - Extract and run, no .NET installation required. - - ### ⌨️ Keyboard Shortcuts - - `Ctrl+Shift+L` - Toggle light on/off - - `Ctrl+Shift+↑` - Increase brightness - - `Ctrl+Shift+↓` - Decrease brightness - - --- - append_body: true - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +name: Build Release + +on: + push: + tags: + - 'v*' + workflow_dispatch: + +permissions: + contents: write + +jobs: + build: + runs-on: windows-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Cache NuGet packages + uses: actions/cache@v4 + with: + path: ~\.nuget\packages + key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }} + restore-keys: | + ${{ runner.os }}-nuget- + + - name: Restore dependencies + run: dotnet restore WindowsEdgeLight/WindowsEdgeLight.csproj + + - name: Install GitVersion + uses: gittools/actions/gitversion/setup@v4 + with: + versionSpec: '6.4.x' + + - name: GitVersion + uses: gittools/actions/gitversion/execute@v4 + id: gitversion + + - name: Set version environment variables + shell: pwsh + run: | + # Use GitVersion outputs for all versioning + $version = '${{ steps.gitversion.outputs.semVer }}' + $fullVersion = '${{ steps.gitversion.outputs.fullSemVer }}' + + # Assembly version must be 4-part (x.y.z.w) + $assemblyVersion = "${{ steps.gitversion.outputs.major }}.${{ steps.gitversion.outputs.minor }}.${{ steps.gitversion.outputs.patch }}.0" + + Write-Host "Using semantic version: $version" + Write-Host "Using full version: $fullVersion" + Write-Host "Using assembly version: $assemblyVersion" + + echo "VERSION=$version" >> $env:GITHUB_ENV + echo "FULLVERSION=$fullVersion" >> $env:GITHUB_ENV + echo "ASSEMBLY_VERSION=$assemblyVersion" >> $env:GITHUB_ENV + + - name: Build x64 + run: | + dotnet publish WindowsEdgeLight/WindowsEdgeLight.csproj ` + -c Release ` + -r win-x64 ` + /p:DebugType=None ` + /p:DebugSymbols=false ` + /p:Version=$env:VERSION ` + /p:AssemblyVersion=$env:ASSEMBLY_VERSION ` + /p:FileVersion=$env:ASSEMBLY_VERSION ` + /p:AssemblyInformationalVersion=$env:FULLVERSION ` + --self-contained + + - name: Build ARM64 + run: | + dotnet publish WindowsEdgeLight/WindowsEdgeLight.csproj ` + -c Release ` + -r win-arm64 ` + /p:DebugType=None ` + /p:DebugSymbols=false ` + /p:Version=$env:VERSION ` + /p:AssemblyVersion=$env:ASSEMBLY_VERSION ` + /p:FileVersion=$env:ASSEMBLY_VERSION ` + /p:AssemblyInformationalVersion=$env:FULLVERSION ` + --self-contained + + - name: Azure Login + uses: azure/login@v2 + with: + creds: '{"clientId":"${{ secrets.AZURE_CLIENT_ID }}","clientSecret":"${{ secrets.AZURE_CLIENT_SECRET }}","subscriptionId":"${{ secrets.AZURE_SUBSCRIPTION_ID }}","tenantId":"${{ secrets.AZURE_TENANT_ID }}"}' + + - name: Sign executables with Trusted Signing + uses: azure/trusted-signing-action@v1 + with: + azure-tenant-id: ${{ secrets.AZURE_TENANT_ID }} + azure-client-id: ${{ secrets.AZURE_CLIENT_ID }} + azure-client-secret: ${{ secrets.AZURE_CLIENT_SECRET }} + endpoint: https://wus2.codesigning.azure.net/ + signing-account-name: hanselman + certificate-profile-name: WindowsEdgeLight + files-folder: ${{ github.workspace }}\WindowsEdgeLight\bin\Release\net10.0-windows + files-folder-filter: exe + files-folder-recurse: true + file-digest: SHA256 + timestamp-rfc3161: http://timestamp.acs.microsoft.com + timestamp-digest: SHA256 + + - name: Prepare artifacts + shell: pwsh + run: | + New-Item -ItemType Directory -Path artifacts -Force + # Use VERSION environment variable (calculated via GitVersion) + $version = $env:VERSION + + # Create ZIP files with exe and README (so Updatum treats as portable app) + New-Item -ItemType Directory -Path "temp-x64" -Force + Copy-Item "WindowsEdgeLight/bin/Release/net10.0-windows/win-x64/publish/WindowsEdgeLight.exe" -Destination "temp-x64/" + Copy-Item "README.md" -Destination "temp-x64/" + Compress-Archive -Path "temp-x64/*" -DestinationPath "artifacts/WindowsEdgeLight-v$version-win-x64.zip" + + New-Item -ItemType Directory -Path "temp-arm64" -Force + Copy-Item "WindowsEdgeLight/bin/Release/net10.0-windows/win-arm64/publish/WindowsEdgeLight.exe" -Destination "temp-arm64/" + Copy-Item "README.md" -Destination "temp-arm64/" + Compress-Archive -Path "temp-arm64/*" -DestinationPath "artifacts/WindowsEdgeLight-v$version-win-arm64.zip" + + Remove-Item "temp-x64" -Recurse -Force + Remove-Item "temp-arm64" -Recurse -Force + + - name: Upload artifacts + uses: actions/upload-artifact@v4 + with: + name: WindowsEdgeLight-Release + path: artifacts/*.zip + + - name: Create Release + if: startsWith(github.ref, 'refs/tags/') + uses: softprops/action-gh-release@v2 + with: + files: artifacts/*.zip + generate_release_notes: true + body: | + ## Windows Edge Light ${{ github.ref_name }} + + ### 📦 Downloads + + | File | Platform | + |------|----------| + | `WindowsEdgeLight-${{ github.ref_name }}-win-x64.zip` | Intel/AMD 64-bit Windows | + | `WindowsEdgeLight-${{ github.ref_name }}-win-arm64.zip` | ARM64 Windows (Surface Pro X, etc.) | + + **Self-contained** - Extract and run, no .NET installation required. + + ### ⌨️ Keyboard Shortcuts + - `Ctrl+Shift+L` - Toggle light on/off + - `Ctrl+Shift+↑` - Increase brightness + - `Ctrl+Shift+↓` - Decrease brightness + + --- + append_body: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6813664 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,44 @@ +name: CI + +on: + pull_request: + push: + branches: + - master + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-and-test: + runs-on: windows-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Cache NuGet packages + uses: actions/cache@v4 + with: + path: ~\.nuget\packages + key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }} + restore-keys: | + ${{ runner.os }}-nuget- + + - name: Restore + run: dotnet restore WindowsEdgeLight.sln + + - name: Build + run: dotnet build WindowsEdgeLight.sln --configuration Release --no-restore + + - name: Test + run: dotnet test WindowsEdgeLight.sln --configuration Release --no-build diff --git a/README.md b/README.md index b34cf18..d0cd90b 100644 --- a/README.md +++ b/README.md @@ -1,203 +1,205 @@ -# Windows Edge Light - -A lightweight WPF application that adds a customizable glowing edge light effect around your primary monitor on Windows. Perfect for ambient lighting during video calls, streaming, or just adding a professional touch to your workspace. - -## Features - -- **Automatic Updates**: Built-in update system checks GitHub Releases for new versions -- **Primary Monitor Display**: Automatically detects and displays on your primary monitor, even in multi-monitor setups -- **DPI Aware**: Properly handles high-DPI displays (4K monitors with scaling) -- **Fluent Design**: Modern UX that fits in with the Windows look and feel -- **Click-Through Transparency**: Overlay doesn't interfere with your work - all clicks pass through to applications beneath -- **Customizable Brightness**: Adjust opacity with easy-to-use controls - - **Adjustable Color Temperature**: Shift the edge light from cooler (blue-ish) to warmer (amber) tones -- **Toggle On/Off**: Quickly enable or disable the edge light effect -- **Hideable Controls**: Hide the control toolbar for a cleaner look, restore via tray menu -- **Always On Top**: Stays visible above all other windows -- **Exclude from Screen Capture**: Optional setting to hide the edge light from screen sharing (Teams, Zoom) and screenshots -- **Keyboard Shortcuts**: - - `Ctrl+Shift+L` - Toggle light on/off - - `Ctrl+Shift+Up` - Increase brightness - - `Ctrl+Shift+Down` - Decrease brightness -- **Gradient Effect**: Beautiful white gradient with subtle blur for a professional look - -## Screenshots - -The application creates a smooth, glowing border around the edges of your primary monitor: - -- Adjustable brightness levels (20% to 100% opacity) -- Soft blur effect for a natural glow -- Minimal UI controls that fade in on hover - -![Windows Edge Light](HeroImage.png) - -## Installation - -### Option 1: Download Pre-built Executable - -Download the latest `WindowsEdgeLight.exe` from the [Releases page](https://github.com/shanselman/WindowsEdgeLight/releases). This is a single-file executable that includes everything you need - no .NET installation required! - -### Option 2: Build from Source - -#### Prerequisites - -- Windows 10 or later -- .NET 10.0 SDK for building - -#### Building from Source - -1. Clone this repository: - ```bash - git clone https://github.com/shanselman/WindowsEdgeLight.git - cd WindowsEdgeLight - ``` - -2. Build the project: - ```bash - cd WindowsEdgeLight - dotnet build - ``` - -3. Run the application: - ```bash - dotnet run - ``` - -#### Creating a Single-File Executable - -To create a standalone executable: -```bash -cd WindowsEdgeLight -dotnet publish -c Release /p:DebugType=None /p:DebugSymbols=false -``` - -The executable will be in `bin\Release\net10.0-windows\win-x64\publish\WindowsEdgeLight.exe` - -**Note**: WPF applications cannot use AOT compilation or aggressive trimming. The single-file executable is self-contained and compressed (~72MB) but includes the full .NET runtime. - -## Usage - -1. Launch `WindowsEdgeLight.exe` -2. The edge light will appear around your primary monitor -3. Control toolbar appears at the bottom center with these buttons: - - 🔅 **Decrease Brightness** - Reduces opacity - - 🔆 **Increase Brightness** - Increases opacity - - 🌡️ **Cooler Color** - Shifts the glow towards a cooler, blue-ish white - - 🔥 **Warmer Color** - Shifts the glow towards a warmer, amber tone - - 💡 **Toggle Light** - Turn the effect on/off - - 🖥️ **Switch Monitor** - Move to next monitor (if multiple monitors) - - 🖥️🖥️ **All Monitors** - Show on all monitors (if multiple monitors) - - 🎥 **Exclude from Capture** - Hide from screen sharing and screenshots - - ✖ **Exit** - Close the application -4. Hide the control toolbar for a cleaner look using the tray menu (right-click tray icon → "Hide Controls") - -### Screen Sharing Mode - -When sharing your screen on video conferencing apps (Teams, Zoom, etc.), you may want the edge light to be visible to you but invisible to viewers. Enable **"Exclude from Screen Capture"** via: -- Click the 🎥 button in the control toolbar, or -- Right-click the tray icon → "Exclude from Screen Capture" - -**Note**: When this setting is enabled, the edge light will also be excluded from screenshots taken with Windows Snipping Tool, PrintScreen, or other capture tools. - -### Keyboard Shortcuts - -- **Ctrl+Shift+L**: Toggle the edge light on/off -- **Ctrl+Shift+Up**: Increase brightness -- **Ctrl+Shift+Down**: Decrease brightness -- **Taskbar**: Right-click the taskbar icon for a menu with toggle, brightness, and color temperature controls - -## Technical Details - -### Architecture - -- **Framework**: .NET 10.0 WPF (Windows Presentation Foundation) -- **Language**: C# -- **UI**: XAML with transparent window overlay -- **Monitor Detection**: Windows Forms Screen API for accurate multi-monitor support - -### Key Features Implementation - -- **Click-Through**: Uses Win32 `WS_EX_TRANSPARENT` and `WS_EX_LAYERED` window styles -- **DPI Scaling**: Converts physical pixels to WPF Device Independent Pixels for proper sizing -- **Primary Monitor**: Uses `Screen.PrimaryScreen.Bounds` with DPI correction -- **Gradient Border**: Custom Rectangle with LinearGradientBrush and BlurEffect - -## Multi-Monitor Support - -The application specifically targets the **primary monitor** in your display setup: -- Automatically detects primary monitor position and dimensions -- Correctly handles DPI scaling (e.g., 150%, 200% on 4K displays) -- Works with any monitor arrangement (horizontal, vertical, mixed) -- Does not span across multiple monitors - -## Development - -### Project Structure - -``` -WindowsEdgeLight/ -├── WindowsEdgeLight/ -│ ├── App.xaml # Application entry point -│ ├── App.xaml.cs -│ ├── MainWindow.xaml # Main UI layout -│ ├── MainWindow.xaml.cs # Application logic -│ ├── WindowsEdgeLight.csproj -│ └── AssemblyInfo.cs -└── README.md -``` - -### Building - -Requires: -- Visual Studio 2022 or later (with .NET desktop development workload) -- Or .NET 10.0 SDK for command-line builds - -## Version History - -**Note**: Versions are automatically managed using GitVersion based on Git tags. - -### v0.6 - Automatic Update System -- Integrated Updatum for automatic updates from GitHub Releases -- Beautiful update dialog with release notes -- Download progress tracking -- One-click install for new versions -- See [UPDATUM_INTEGRATION.md](UPDATUM_INTEGRATION.md) for details - -### v0.3 - Global Hotkeys and Taskbar Support -- Added global hotkeys for brightness control (Ctrl+Shift+Up/Down) -- Fixed taskbar overlap - window now respects taskbar area -- Added taskbar icon for easy right-click close -- Removed conflicting exit hotkey -- Added custom ring light icon -- Added assembly information with author details - -### v0.2 - Primary Monitor Display Fix -- Fixed window to display on primary monitor only -- Added proper DPI scaling support for high-resolution displays -- Resolved namespace conflicts with Windows Forms integration -- Improved multi-monitor setup compatibility - -### v0.1 - Initial Release -- Basic edge light overlay functionality -- Customizable brightness controls -- Toggle and keyboard shortcut support -- Click-through transparency - -## License - -This project is provided as-is for personal and educational use. - -## Contributing - -Contributions are welcome! Feel free to: -- Report bugs -- Suggest new features -- Submit pull requests - -## Acknowledgments - -Inspired by the need for professional lighting effects during video conferences and streaming setups. - ---- - -**Note**: This application is designed for Windows only and requires the .NET 10.0 runtime. +# Windows Edge Light + +A lightweight WPF application that adds a customizable glowing edge light effect around your monitors on Windows. Perfect for ambient lighting during video calls, streaming, or just adding a professional touch to your workspace. + +## Features + +- **Automatic Updates**: Built-in update system checks GitHub Releases for new versions +- **Multi-Monitor Support**: Display on your primary monitor, switch to another monitor, or show on all monitors simultaneously +- **DPI Aware**: Properly handles high-DPI displays (4K monitors with scaling) +- **Fluent Design**: Modern UX that fits in with the Windows look and feel +- **Click-Through Transparency**: Overlay doesn't interfere with your work - all clicks pass through to applications beneath +- **Customizable Brightness**: Adjust opacity with easy-to-use controls +- **Adjustable Color Temperature**: Shift the edge light from cooler (blue-ish) to warmer (amber) tones +- **Toggle On/Off**: Quickly enable or disable the edge light effect +- **Hideable Controls**: Hide the control toolbar for a cleaner look, restore via tray menu +- **Always On Top**: Stays visible above all other windows +- **Persistent Settings**: Brightness, color temperature, on/off state, and preferences are saved across restarts +- **Settings Window**: Dedicated settings panel with sliders and control-bar customization +- **Exclude from Screen Capture**: Optional setting to hide the edge light from screen sharing (Teams, Zoom) and screenshots +- **Keyboard Shortcuts**: + - `Ctrl+Shift+L` - Toggle light on/off + - `Ctrl+Shift+Up` - Increase brightness + - `Ctrl+Shift+Down` - Decrease brightness +- **Gradient Effect**: Beautiful white gradient with subtle blur for a professional look + +## Screenshots + +The application creates a smooth, glowing border around the edges of your primary monitor: + +- Adjustable brightness levels (20% to 100% opacity) +- Soft blur effect for a natural glow +- Minimal UI controls that fade in on hover + +![Windows Edge Light](HeroImage.png) + +## Installation + +### Option 1: Download Pre-built Executable + +Download the latest `WindowsEdgeLight.exe` from the [Releases page](https://github.com/shanselman/WindowsEdgeLight/releases). This is a single-file executable that includes everything you need - no .NET installation required! + +### Option 2: Build from Source + +#### Prerequisites + +- Windows 10 or later +- .NET 10.0 SDK for building + +#### Building from Source + +1. Clone this repository: + ```bash + git clone https://github.com/shanselman/WindowsEdgeLight.git + cd WindowsEdgeLight + ``` + +2. Build the project: + ```bash + cd WindowsEdgeLight + dotnet build + ``` + +3. Run the application: + ```bash + dotnet run + ``` + +#### Creating a Single-File Executable + +To create a standalone executable: +```bash +cd WindowsEdgeLight +dotnet publish -c Release /p:DebugType=None /p:DebugSymbols=false +``` + +The executable will be in `bin\Release\net10.0-windows\win-x64\publish\WindowsEdgeLight.exe` + +**Note**: WPF applications cannot use AOT compilation or aggressive trimming. The single-file executable is self-contained and compressed (~72MB) but includes the full .NET runtime. + +## Usage + +1. Launch `WindowsEdgeLight.exe` +2. The edge light will appear around your primary monitor +3. Control toolbar appears at the bottom center with these buttons: + - 🔅 **Decrease Brightness** - Reduces opacity + - 🔆 **Increase Brightness** - Increases opacity + - 🔥 **Warmer Color** - Shifts the glow towards a warmer, amber tone + - ❄️ **Cooler Color** - Shifts the glow towards a cooler, blue-ish white + - 💡 **Toggle Light** - Turn the effect on/off + - 🖥️ **Switch Monitor** - Move to next monitor (if multiple monitors) + - 🖥️🖥️ **All Monitors** - Show on all monitors (if multiple monitors) + - ⚙️ **Settings** - Adjust appearance, capture exclusion, and control visibility + - ✖ **Exit** - Close the application +4. Hide the control toolbar for a cleaner look using the tray menu (right-click tray icon → "Hide Controls") + +### Screen Sharing Mode + +When sharing your screen on video conferencing apps (Teams, Zoom, etc.), you may want the edge light to be visible to you but invisible to viewers. Enable **"Exclude from Screen Capture"** via: +- Open ⚙️ **Settings** from the control toolbar and enable **Exclude from Screen Capture**, or +- Right-click the tray icon → "Exclude from Screen Capture" + +**Note**: When this setting is enabled, the edge light will also be excluded from screenshots taken with Windows Snipping Tool, PrintScreen, or other capture tools. + +### Keyboard Shortcuts + +- **Ctrl+Shift+L**: Toggle the edge light on/off +- **Ctrl+Shift+Up**: Increase brightness +- **Ctrl+Shift+Down**: Decrease brightness +- **Taskbar**: Right-click the taskbar icon for a menu with toggle, brightness, and color temperature controls + +## Technical Details + +### Architecture + +- **Framework**: .NET 10.0 WPF (Windows Presentation Foundation) +- **Language**: C# +- **UI**: XAML with transparent window overlay +- **Monitor Detection**: Windows Forms Screen API for accurate multi-monitor support + +### Key Features Implementation + +- **Click-Through**: Uses Win32 `WS_EX_TRANSPARENT` and `WS_EX_LAYERED` window styles +- **DPI Scaling**: Converts physical pixels to WPF Device Independent Pixels for proper sizing +- **Primary Monitor**: Uses `Screen.PrimaryScreen.Bounds` with DPI correction +- **Gradient Border**: Custom Rectangle with LinearGradientBrush and BlurEffect + +## Multi-Monitor Support + +The application supports flexible multi-monitor configurations: +- Starts on the primary monitor +- Switches between connected monitors from the toolbar or tray menu +- Can display the edge light on every connected monitor simultaneously +- Handles per-monitor DPI scaling and mixed monitor arrangements + +## Development + +### Project Structure + +``` +WindowsEdgeLight/ +├── WindowsEdgeLight/ +│ ├── App.xaml # Application entry point +│ ├── App.xaml.cs +│ ├── MainWindow.xaml # Main UI layout +│ ├── MainWindow.xaml.cs # Application logic +│ ├── WindowsEdgeLight.csproj +│ └── AssemblyInfo.cs +└── README.md +``` + +### Building + +Requires: +- Visual Studio 2022 or later (with .NET desktop development workload) +- Or .NET 10.0 SDK for command-line builds + +## Version History + +**Note**: Versions are automatically managed using GitVersion based on Git tags. + +### v0.6 - Automatic Update System +- Integrated Updatum for automatic updates from GitHub Releases +- Beautiful update dialog with release notes +- Download progress tracking +- One-click install for new versions +- See [UPDATUM_INTEGRATION.md](UPDATUM_INTEGRATION.md) for details + +### v0.3 - Global Hotkeys and Taskbar Support +- Added global hotkeys for brightness control (Ctrl+Shift+Up/Down) +- Fixed taskbar overlap - window now respects taskbar area +- Added taskbar icon for easy right-click close +- Removed conflicting exit hotkey +- Added custom ring light icon +- Added assembly information with author details + +### v0.2 - Primary Monitor Display Fix +- Fixed window to display on primary monitor only +- Added proper DPI scaling support for high-resolution displays +- Resolved namespace conflicts with Windows Forms integration +- Improved multi-monitor setup compatibility + +### v0.1 - Initial Release +- Basic edge light overlay functionality +- Customizable brightness controls +- Toggle and keyboard shortcut support +- Click-through transparency + +## License + +This project is provided as-is for personal and educational use. + +## Contributing + +Contributions are welcome! Feel free to: +- Report bugs +- Suggest new features +- Submit pull requests + +## Acknowledgments + +Inspired by the need for professional lighting effects during video conferences and streaming setups. + +--- + +**Note**: This application is designed for Windows only and requires the .NET 10.0 runtime. diff --git a/WindowsEdgeLight.Tests/AppSettingsTests.cs b/WindowsEdgeLight.Tests/AppSettingsTests.cs new file mode 100644 index 0000000..35bc3a0 --- /dev/null +++ b/WindowsEdgeLight.Tests/AppSettingsTests.cs @@ -0,0 +1,137 @@ +using System.Text.Json; +using Xunit; + +namespace WindowsEdgeLight.Tests; + +public sealed class AppSettingsTests : IDisposable +{ + private readonly string tempDirectory = Path.Combine( + Path.GetTempPath(), + $"WindowsEdgeLight.Tests-{Guid.NewGuid():N}"); + + private string SettingsPath => Path.Combine(tempDirectory, "settings.json"); + + [Fact] + public void DefaultsMatchApplicationDefaults() + { + var settings = new AppSettings(); + + Assert.True(settings.ExcludeFromCapture); + Assert.True(settings.IsLightOn); + Assert.Equal(1.0, settings.Brightness); + Assert.Equal(0.5, settings.ColorTemperature); + Assert.True(settings.ShowToggleButton); + Assert.True(settings.ShowBrightnessButtons); + Assert.True(settings.ShowColorTempButtons); + Assert.True(settings.ShowMonitorControlButtons); + } + + [Fact] + public void MissingFileReturnsDefaults() + { + var settings = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(1.0, settings.Brightness); + Assert.True(settings.IsLightOn); + } + + [Fact] + public void SaveAndLoadRoundTripsAllProperties() + { + var expected = new AppSettings + { + ExcludeFromCapture = false, + IsLightOn = false, + Brightness = 0.7, + ColorTemperature = 0.3, + ShowToggleButton = false, + ShowBrightnessButtons = false, + ShowColorTempButtons = false, + ShowMonitorControlButtons = false + }; + + expected.SaveTo(SettingsPath); + var actual = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(expected.ExcludeFromCapture, actual.ExcludeFromCapture); + Assert.Equal(expected.IsLightOn, actual.IsLightOn); + Assert.Equal(expected.Brightness, actual.Brightness); + Assert.Equal(expected.ColorTemperature, actual.ColorTemperature); + Assert.Equal(expected.ShowToggleButton, actual.ShowToggleButton); + Assert.Equal(expected.ShowBrightnessButtons, actual.ShowBrightnessButtons); + Assert.Equal(expected.ShowColorTempButtons, actual.ShowColorTempButtons); + Assert.Equal(expected.ShowMonitorControlButtons, actual.ShowMonitorControlButtons); + Assert.False(File.Exists(SettingsPath + ".tmp")); + } + + [Fact] + public void SaveReplacesExistingFile() + { + Directory.CreateDirectory(tempDirectory); + File.WriteAllText(SettingsPath, """{"Brightness":0.2}"""); + var settings = new AppSettings { Brightness = 0.8 }; + + settings.SaveTo(SettingsPath); + + Assert.Equal(0.8, AppSettings.LoadFrom(SettingsPath).Brightness); + Assert.False(File.Exists(SettingsPath + ".tmp")); + } + + [Fact] + public void SaveCreatesParentDirectory() + { + var nestedPath = Path.Combine(tempDirectory, "nested", "settings.json"); + + new AppSettings().SaveTo(nestedPath); + + Assert.True(File.Exists(nestedPath)); + } + + [Fact] + public void CorruptJsonReturnsDefaultsAndDeletesFile() + { + Directory.CreateDirectory(tempDirectory); + File.WriteAllText(SettingsPath, "{ invalid"); + + var settings = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(1.0, settings.Brightness); + Assert.False(File.Exists(SettingsPath)); + } + + [Fact] + public void CommentsAndTrailingCommasAreAccepted() + { + Directory.CreateDirectory(tempDirectory); + File.WriteAllText(SettingsPath, """ + { + // User-edited settings remain supported. + "Brightness": 0.6, + "ColorTemperature": 0.2, + } + """); + + var settings = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(0.6, settings.Brightness); + Assert.Equal(0.2, settings.ColorTemperature); + } + + [Fact] + public void SavedJsonIsIndented() + { + new AppSettings().SaveTo(SettingsPath); + + var json = File.ReadAllText(SettingsPath); + Assert.Contains(Environment.NewLine, json); + Assert.NotNull(JsonSerializer.Deserialize(json)); + } + + public void Dispose() + { + if (Directory.Exists(tempDirectory)) + { + Directory.Delete(tempDirectory, recursive: true); + } + } +} diff --git a/WindowsEdgeLight.Tests/WindowsEdgeLight.Tests.csproj b/WindowsEdgeLight.Tests/WindowsEdgeLight.Tests.csproj new file mode 100644 index 0000000..ffef641 --- /dev/null +++ b/WindowsEdgeLight.Tests/WindowsEdgeLight.Tests.csproj @@ -0,0 +1,24 @@ + + + + net10.0-windows + enable + enable + false + true + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/WindowsEdgeLight.sln b/WindowsEdgeLight.sln index 6ea1e8e..44ffdf8 100644 --- a/WindowsEdgeLight.sln +++ b/WindowsEdgeLight.sln @@ -1,24 +1,30 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.5.2.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsEdgeLight", "WindowsEdgeLight\WindowsEdgeLight.csproj", "{C2187EC4-5511-1F4A-A7C5-D7D114D039DC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {A907C696-8323-4246-BE77-DEBB79E9D8A5} - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.2.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsEdgeLight", "WindowsEdgeLight\WindowsEdgeLight.csproj", "{C2187EC4-5511-1F4A-A7C5-D7D114D039DC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsEdgeLight.Tests", "WindowsEdgeLight.Tests\WindowsEdgeLight.Tests.csproj", "{B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Release|Any CPU.Build.0 = Release|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A907C696-8323-4246-BE77-DEBB79E9D8A5} + EndGlobalSection +EndGlobal diff --git a/WindowsEdgeLight/AppSettings.cs b/WindowsEdgeLight/AppSettings.cs index 1f46de9..eab3547 100644 --- a/WindowsEdgeLight/AppSettings.cs +++ b/WindowsEdgeLight/AppSettings.cs @@ -1,128 +1,137 @@ -using System; -using System.IO; -using System.Text.Json; - -namespace WindowsEdgeLight; - -/// -/// Application settings that persist across sessions -/// -public class AppSettings -{ - private static readonly string SettingsFilePath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "WindowsEdgeLight", - "settings.json"); - - /// - /// When enabled, excludes the edge light from screen capture (Teams, screenshots, etc.) - /// Note: When enabled, screenshots won't capture the edge light effect - /// - public bool ExcludeFromCapture { get; set; } = true; - - /// - /// Whether the edge light is on or off (persisted across restarts) - /// - public bool IsLightOn { get; set; } = true; - - /// - /// Brightness/opacity of the edge light, in the range [0.2, 1.0] - /// - public double Brightness { get; set; } = 1.0; - - /// - /// Color temperature of the edge light, in the range [0.0, 1.0] - /// where 0.0 = coolest (blue-white) and 1.0 = warmest (amber) - /// - public double ColorTemperature { get; set; } = 0.5; - - /// - /// Whether to show toggle button in the control window - /// - public bool ShowToggleButton { get; set; } = true; - - /// - /// Whether to show brightness buttons in the control window - /// - public bool ShowBrightnessButtons { get; set; } = true; - - /// - /// Whether to show color temperature buttons in the control window - /// - public bool ShowColorTempButtons { get; set; } = true; - - /// - /// Whether to show window control buttons (toggle, switch monitor, all monitors) in the control window - /// - public bool ShowMonitorControlButtons { get; set; } = true; - - /// - /// Load settings from disk - /// - public static AppSettings Load() - { - try - { - if (File.Exists(SettingsFilePath)) - { - var json = File.ReadAllText(SettingsFilePath); - var options = new JsonSerializerOptions - { - AllowTrailingCommas = true, - ReadCommentHandling = JsonCommentHandling.Skip - }; - var settings = JsonSerializer.Deserialize(json, options); - - // Validate deserialized settings - if (settings != null) - { - return settings; - } - } - } - catch (JsonException ex) - { - System.Diagnostics.Debug.WriteLine($"Failed to parse settings file: {ex.Message}"); - // Delete corrupted settings file - try - { - if (File.Exists(SettingsFilePath)) - { - File.Delete(SettingsFilePath); - } - } - catch { /* Ignore deletion errors */ } - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine($"Failed to load settings: {ex.Message}"); - } - - return new AppSettings(); - } - - /// - /// Save settings to disk - /// - public void Save() - { - try - { - var directory = Path.GetDirectoryName(SettingsFilePath); - if (directory != null && !Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } - - var json = JsonSerializer.Serialize(this, new JsonSerializerOptions - { - WriteIndented = true - }); - File.WriteAllText(SettingsFilePath, json); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine($"Failed to save settings: {ex.Message}"); - } - } -} +using System; +using System.IO; +using System.Text.Json; + +namespace WindowsEdgeLight; + +/// +/// Application settings that persist across sessions +/// +public class AppSettings +{ + private static readonly string SettingsFilePath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "WindowsEdgeLight", + "settings.json"); + + private static readonly JsonSerializerOptions ReadOptions = new() + { + AllowTrailingCommas = true, + ReadCommentHandling = JsonCommentHandling.Skip + }; + + private static readonly JsonSerializerOptions WriteOptions = new() + { + WriteIndented = true + }; + + /// + /// When enabled, excludes the edge light from screen capture (Teams, screenshots, etc.) + /// Note: When enabled, screenshots won't capture the edge light effect + /// + public bool ExcludeFromCapture { get; set; } = true; + + /// + /// Whether the edge light is on or off (persisted across restarts) + /// + public bool IsLightOn { get; set; } = true; + + /// + /// Brightness/opacity of the edge light, in the range [0.2, 1.0] + /// + public double Brightness { get; set; } = 1.0; + + /// + /// Color temperature of the edge light, in the range [0.0, 1.0] + /// where 0.0 = coolest (blue-white) and 1.0 = warmest (amber) + /// + public double ColorTemperature { get; set; } = 0.5; + + /// + /// Whether to show toggle button in the control window + /// + public bool ShowToggleButton { get; set; } = true; + + /// + /// Whether to show brightness buttons in the control window + /// + public bool ShowBrightnessButtons { get; set; } = true; + + /// + /// Whether to show color temperature buttons in the control window + /// + public bool ShowColorTempButtons { get; set; } = true; + + /// + /// Whether to show window control buttons (toggle, switch monitor, all monitors) in the control window + /// + public bool ShowMonitorControlButtons { get; set; } = true; + + /// + /// Load settings from disk + /// + public static AppSettings Load() => LoadFrom(SettingsFilePath); + + internal static AppSettings LoadFrom(string filePath) + { + try + { + if (File.Exists(filePath)) + { + var json = File.ReadAllText(filePath); + var settings = JsonSerializer.Deserialize(json, ReadOptions); + + // Validate deserialized settings + if (settings != null) + { + return settings; + } + } + } + catch (JsonException ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to parse settings file: {ex.Message}"); + // Delete corrupted settings file + try + { + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + } + catch { /* Ignore deletion errors */ } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to load settings: {ex.Message}"); + } + + return new AppSettings(); + } + + /// + /// Save settings to disk + /// + public void Save() => SaveTo(SettingsFilePath); + + internal void SaveTo(string filePath) + { + try + { + var directory = Path.GetDirectoryName(filePath); + if (directory != null && !Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + + var json = JsonSerializer.Serialize(this, WriteOptions); + var tempPath = filePath + ".tmp"; + File.WriteAllText(tempPath, json); + File.Move(tempPath, filePath, overwrite: true); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to save settings: {ex.Message}"); + } + } +} diff --git a/WindowsEdgeLight/AssemblyInfo.cs b/WindowsEdgeLight/AssemblyInfo.cs index cc29e7f..fa836ed 100644 --- a/WindowsEdgeLight/AssemblyInfo.cs +++ b/WindowsEdgeLight/AssemblyInfo.cs @@ -1,10 +1,13 @@ -using System.Windows; - -[assembly:ThemeInfo( - ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, - // or application resource dictionaries) - ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, - // app, or any theme specific resource dictionaries) -)] +using System.Windows; +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("WindowsEdgeLight.Tests")] + +[assembly:ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/WindowsEdgeLight/ControlWindow.xaml.cs b/WindowsEdgeLight/ControlWindow.xaml.cs index 871d03d..49e0f56 100644 --- a/WindowsEdgeLight/ControlWindow.xaml.cs +++ b/WindowsEdgeLight/ControlWindow.xaml.cs @@ -1,113 +1,119 @@ -using System.Windows; -using System.Windows.Input; - -namespace WindowsEdgeLight; - -public partial class ControlWindow : Window -{ - private readonly MainWindow mainWindow; - - public ControlWindow(MainWindow main) - { - InitializeComponent(); - mainWindow = main; - - UpdateMonitorButtonState(); - ApplyButtonVisibility(); - } - - private void UpdateMonitorButtonState() - { - SwitchMonitorButton.IsEnabled = mainWindow.HasMultipleMonitors() && !mainWindow.IsShowingOnAllMonitors(); - AllMonitorsButton.IsEnabled = mainWindow.HasMultipleMonitors(); - } - - public void ApplyButtonVisibility() - { - var toggleButtonVis = mainWindow.GetIsToggleButtonVisible() ? Visibility.Visible : Visibility.Collapsed; - var brightVis = mainWindow.GetIsBrightnessButtonsVisible() ? Visibility.Visible : Visibility.Collapsed; - var tempVis = mainWindow.GetIsColorTempButtonsVisible() ? Visibility.Visible : Visibility.Collapsed; - var monitorCtrlVis = mainWindow.GetIsControlMonitorsButtonVisible() ? Visibility.Visible : Visibility.Collapsed; - - ToggleLightButton.Visibility = toggleButtonVis; - BrightnessDownButton.Visibility = brightVis; - BrightnessUpButton.Visibility = brightVis; - ColorWarmerButton.Visibility = tempVis; - ColorCoolerButton.Visibility = tempVis; - SwitchMonitorButton.Visibility = monitorCtrlVis; - AllMonitorsButton.Visibility = monitorCtrlVis; - } - - public void UpdateAllMonitorsButtonState() - { - UpdateMonitorButtonState(); - } - - private void BrightnessDown_Click(object sender, RoutedEventArgs e) - { - mainWindow.DecreaseBrightness(); - } - - private void BrightnessUp_Click(object sender, RoutedEventArgs e) - { - mainWindow.IncreaseBrightness(); - } - - private void ColorCooler_Click(object sender, RoutedEventArgs e) - { - mainWindow.DecreaseColorTemperature(); - } - - private void ColorWarmer_Click(object sender, RoutedEventArgs e) - { - mainWindow.IncreaseColorTemperature(); - } - - private void Toggle_Click(object sender, RoutedEventArgs e) - { - mainWindow.HandleToggle(); - } - - private void SwitchMonitor_Click(object sender, RoutedEventArgs e) - { - mainWindow.MoveToNextMonitor(); - UpdateMonitorButtonState(); - } - - private void AllMonitors_Click(object sender, RoutedEventArgs e) - { - mainWindow.ToggleAllMonitors(); - } - - private void Open_Settings(object sender, RoutedEventArgs e) - { - var settings = new SettingsWindow(mainWindow); - settings.Owner = this; - settings.ShowDialog(); - ApplyButtonVisibility(); - } - - private void DragHandle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) - { - if (e.LeftButton != MouseButtonState.Pressed) - { - return; - } - - mainWindow.NotifyControlWindowManuallyMoved(); - - try - { - DragMove(); - } - catch (System.InvalidOperationException) - { - // DragMove can throw if the mouse button is no longer pressed; ignore. - } - } - - private void Close_Click(object sender, RoutedEventArgs e) - { - System.Windows.Application.Current.Shutdown(); - } -} +using System.Windows; +using System.Windows.Input; + +namespace WindowsEdgeLight; + +public partial class ControlWindow : Window +{ + private readonly MainWindow mainWindow; + + public ControlWindow(MainWindow main) + { + InitializeComponent(); + mainWindow = main; + + UpdateMonitorButtonState(); + ApplyButtonVisibility(); + } + + private void UpdateMonitorButtonState() + { + SwitchMonitorButton.IsEnabled = mainWindow.HasMultipleMonitors() && !mainWindow.IsShowingOnAllMonitors(); + AllMonitorsButton.IsEnabled = mainWindow.HasMultipleMonitors(); + } + + public void ApplyButtonVisibility() + { + var toggleButtonVis = mainWindow.GetIsToggleButtonVisible() ? Visibility.Visible : Visibility.Collapsed; + var brightVis = mainWindow.GetIsBrightnessButtonsVisible() ? Visibility.Visible : Visibility.Collapsed; + var tempVis = mainWindow.GetIsColorTempButtonsVisible() ? Visibility.Visible : Visibility.Collapsed; + var monitorCtrlVis = mainWindow.GetIsControlMonitorsButtonVisible() ? Visibility.Visible : Visibility.Collapsed; + + ToggleLightButton.Visibility = toggleButtonVis; + BrightnessDownButton.Visibility = brightVis; + BrightnessUpButton.Visibility = brightVis; + ColorWarmerButton.Visibility = tempVis; + ColorCoolerButton.Visibility = tempVis; + SwitchMonitorButton.Visibility = monitorCtrlVis; + AllMonitorsButton.Visibility = monitorCtrlVis; + } + + public void UpdateAllMonitorsButtonState() + { + UpdateMonitorButtonState(); + } + + private void BrightnessDown_Click(object sender, RoutedEventArgs e) + { + mainWindow.DecreaseBrightness(); + } + + private void BrightnessUp_Click(object sender, RoutedEventArgs e) + { + mainWindow.IncreaseBrightness(); + } + + private void ColorCooler_Click(object sender, RoutedEventArgs e) + { + mainWindow.DecreaseColorTemperature(); + } + + private void ColorWarmer_Click(object sender, RoutedEventArgs e) + { + mainWindow.IncreaseColorTemperature(); + } + + private void Toggle_Click(object sender, RoutedEventArgs e) + { + mainWindow.HandleToggle(); + } + + private void SwitchMonitor_Click(object sender, RoutedEventArgs e) + { + mainWindow.MoveToNextMonitor(); + UpdateMonitorButtonState(); + } + + private void AllMonitors_Click(object sender, RoutedEventArgs e) + { + mainWindow.ToggleAllMonitors(); + } + + private void Open_Settings(object sender, RoutedEventArgs e) + { + var settings = new SettingsWindow(mainWindow); + settings.Owner = this; + settings.ShowDialog(); + ApplyButtonVisibility(); + } + + private void DragHandle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + if (e.LeftButton != MouseButtonState.Pressed) + { + return; + } + + var initialLeft = Left; + var initialTop = Top; + + try + { + DragMove(); + } + catch (System.InvalidOperationException) + { + // DragMove can throw if the mouse button is no longer pressed; ignore. + } + + if (Math.Abs(Left - initialLeft) > 0.5 || Math.Abs(Top - initialTop) > 0.5) + { + mainWindow.NotifyControlWindowManuallyMoved(); + } + } + + private void Close_Click(object sender, RoutedEventArgs e) + { + System.Windows.Application.Current.Shutdown(); + } +} diff --git a/WindowsEdgeLight/MainWindow.xaml.cs b/WindowsEdgeLight/MainWindow.xaml.cs index 2cf0f38..f1a7558 100644 --- a/WindowsEdgeLight/MainWindow.xaml.cs +++ b/WindowsEdgeLight/MainWindow.xaml.cs @@ -1,1442 +1,1473 @@ -using System.IO; -using System.Runtime.InteropServices; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; -using System.Windows.Interop; -using System.Windows.Media; -using System.Windows.Shapes; -using System.Windows.Threading; - -namespace WindowsEdgeLight; - -public partial class MainWindow : Window -{ - private bool isLightOn = true; - private double currentOpacity = 1.0; // Full brightness by default - private const double OpacityStep = 0.15; - private const double MinOpacity = 0.2; - private const double MaxOpacity = 1.0; - - - // Color temperature ("cool" blue-ish to "warm" amber-ish) - // We'll model this as a simple 0-1 slider where 0 = coolest, 1 = warmest. - private double _colorTemperature = 0.5; - private const double ColorTempStep = 0.1; - private const double MinColorTemp = 0.0; - private const double MaxColorTemp = 1.0; - - // DPI Scale - private double _dpiScaleX = 1.0; - private double _dpiScaleY = 1.0; - - private bool _isManualMonitorSwitch = false; - - private NotifyIcon? notifyIcon; - private ControlWindow? controlWindow; - // Tracks whether the control window should be visible (controls initial visibility and toggle state) - private bool isControlWindowVisible = true; - // Session-only: once the user drags the control toolbar, stop auto-repositioning it. - private bool controlWindowManuallyMoved = false; - private ToolStripMenuItem? toggleControlsMenuItem; - private ToolStripMenuItem? excludeFromCaptureMenuItem; - - // Application settings - private AppSettings settings = new AppSettings(); - - private class MonitorWindowContext - { - public Window Window { get; set; } = null!; - public Screen Screen { get; set; } = null!; - public System.Windows.Shapes.Path BorderPath { get; set; } = null!; - public Ellipse HoverRing { get; set; } = null!; - public Geometry BaseGeometry { get; set; } = null!; - public Rect FrameOuterRect { get; set; } - public Rect FrameInnerRect { get; set; } - public double PathOffsetX { get; set; } - public double PathOffsetY { get; set; } - public double DpiScaleX { get; set; } = 1.0; - public double DpiScaleY { get; set; } = 1.0; - } - - // Monitor management - private int currentMonitorIndex = 0; - private Screen[] availableMonitors = Array.Empty(); - private bool showOnAllMonitors = false; - private List additionalMonitorWindows = new List(); - - // Global hotkey IDs - private const int HOTKEY_TOGGLE = 1; - private const int HOTKEY_BRIGHTNESS_UP = 2; - private const int HOTKEY_BRIGHTNESS_DOWN = 3; - - [DllImport("user32.dll")] - private static extern int GetSystemMetrics(int nIndex); - private const int SM_CXSCREEN = 0; - private const int SM_CYSCREEN = 1; - - [DllImport("user32.dll")] - private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); - - [DllImport("user32.dll")] - private static extern bool UnregisterHotKey(IntPtr hWnd, int id); - - [DllImport("user32.dll", SetLastError = true)] - private static extern bool SetWindowDisplayAffinity(IntPtr hWnd, uint dwAffinity); - - private const uint WDA_NONE = 0x00000000; - private const uint WDA_EXCLUDEFROMCAPTURE = 0x00000011; - - [DllImport("user32.dll")] - private static extern IntPtr MonitorFromPoint(POINT pt, uint dwFlags); - - [DllImport("shcore.dll")] - private static extern int GetDpiForMonitor(IntPtr hmonitor, int dpiType, out uint dpiX, out uint dpiY); - - private const int MDT_EFFECTIVE_DPI = 0; - private const uint MONITOR_DEFAULTTONEAREST = 2; - - [StructLayout(LayoutKind.Sequential)] - private struct POINT - { - public int x; // lowercase to match existing usage - public int y; - } - - // Mouse hook P/Invoke declarations - [DllImport("user32.dll", SetLastError = true)] - private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId); - - [DllImport("user32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool UnhookWindowsHookEx(IntPtr hhk); - - [DllImport("user32.dll")] - private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); - - [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern IntPtr GetModuleHandle(string lpModuleName); - - private const int WH_MOUSE_LL = 14; - private const int WM_MOUSEMOVE = 0x0200; - - [StructLayout(LayoutKind.Sequential)] - private struct MSLLHOOKSTRUCT - { - public POINT pt; - public uint mouseData; - public uint flags; - public uint time; - public IntPtr dwExtraInfo; - } - - private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam); - - // Mouse hook management - private IntPtr mouseHookHandle = IntPtr.Zero; - private LowLevelMouseProc? mouseHookCallback; - - private Rect? frameOuterRect; - private Rect? frameInnerRect; - private readonly Ellipse? hoverCursorRing; - // Added fields for hole effect - private Geometry? baseFrameGeometry; // original frame geometry (outer minus inner) - private double pathOffsetX; // offset of geometry within window - private double pathOffsetY; - - private const uint MOD_CONTROL = 0x0002; - private const uint MOD_SHIFT = 0x0004; - private const uint VK_L = 0x4C; - private const uint VK_UP = 0x26; - private const uint VK_DOWN = 0x28; - - public MainWindow() - { - InitializeComponent(); - hoverCursorRing = FindName("HoverCursorRing") as Ellipse; - - // Load settings - settings = AppSettings.Load(); - - // Restore persisted state - isLightOn = settings.IsLightOn; - currentOpacity = Math.Max(MinOpacity, Math.Min(MaxOpacity, settings.Brightness)); - _colorTemperature = Math.Max(MinColorTemp, Math.Min(MaxColorTemp, settings.ColorTemperature)); - - // Save back if values were clamped - if (currentOpacity != settings.Brightness || _colorTemperature != settings.ColorTemperature) - { - settings.Brightness = currentOpacity; - settings.ColorTemperature = _colorTemperature; - settings.Save(); - } - - SetupNotifyIcon(); - } - - private void SetupNotifyIcon() - { - notifyIcon = new NotifyIcon(); - - // Load icon from embedded resource or file - try - { - var iconPath = System.IO.Path.Combine(AppContext.BaseDirectory, "ringlight_cropped.ico"); - if (File.Exists(iconPath)) - { - notifyIcon.Icon = new System.Drawing.Icon(iconPath); - } - else - { - // Try application icon from exe - var appIcon = System.Drawing.Icon.ExtractAssociatedIcon(Environment.ProcessPath ?? System.Reflection.Assembly.GetExecutingAssembly().Location); - notifyIcon.Icon = appIcon ?? System.Drawing.SystemIcons.Application; - } - } - catch (Exception) - { - // Fallback to default icon if loading fails - notifyIcon.Icon = System.Drawing.SystemIcons.Application; - } - - notifyIcon.Text = "Windows Edge Light - Right-click for options"; - notifyIcon.Visible = true; - - var contextMenu = new ContextMenuStrip(); - contextMenu.Items.Add("📋 Keyboard Shortcuts", null, (s, e) => ShowHelp()); - contextMenu.Items.Add(new ToolStripSeparator()); - contextMenu.Items.Add("💡 Toggle Light (Ctrl+Shift+L)", null, (s, e) => ToggleLight()); - contextMenu.Items.Add("🔆 Brightness Up (Ctrl+Shift+↑)", null, (s, e) => IncreaseBrightness()); - contextMenu.Items.Add("🔅 Brightness Down (Ctrl+Shift+↓)", null, (s, e) => DecreaseBrightness()); - contextMenu.Items.Add(new ToolStripSeparator()); - contextMenu.Items.Add("🔥 K- Warmer Light", null, (s, e) => IncreaseColorTemperature()); - contextMenu.Items.Add("❄️ K+ Cooler Light", null, (s, e) => DecreaseColorTemperature()); - contextMenu.Items.Add(new ToolStripSeparator()); - contextMenu.Items.Add("🖥️ Switch Monitor", null, (s, e) => MoveToNextMonitor()); - contextMenu.Items.Add("🖥️🖥️ Toggle All Monitors", null, (s, e) => ToggleAllMonitors()); - contextMenu.Items.Add(new ToolStripSeparator()); - - // Add toggle controls menu item - text will be set by UpdateTrayMenuToggleControlsText - toggleControlsMenuItem = new ToolStripMenuItem("🎛️ Hide Controls", null, (s, e) => ToggleControlsVisibility()); - contextMenu.Items.Add(toggleControlsMenuItem); - - // Add exclude from capture menu item with checkmark - excludeFromCaptureMenuItem = new ToolStripMenuItem("🎥 Exclude from Screen Capture", null, (s, e) => ToggleExcludeFromCapture()); - excludeFromCaptureMenuItem.CheckOnClick = true; - excludeFromCaptureMenuItem.Checked = settings.ExcludeFromCapture; - contextMenu.Items.Add(excludeFromCaptureMenuItem); - - contextMenu.Items.Add(new ToolStripSeparator()); - contextMenu.Items.Add("✖ Exit", null, (s, e) => System.Windows.Application.Current.Shutdown()); - - notifyIcon.ContextMenuStrip = contextMenu; - notifyIcon.DoubleClick += (s, e) => ShowHelp(); - - // Set initial menu text based on current state - UpdateTrayMenuToggleControlsText(); - } - - private void ShowHelp() - { - var version = System.Reflection.Assembly.GetExecutingAssembly() - .GetName().Version?.ToString() ?? "Unknown"; - - var helpMessage = $@"Windows Edge Light - Keyboard Shortcuts - -💡 Toggle Light: Ctrl + Shift + L -🔆 Brightness Up: Ctrl + Shift + ↑ -🔅 Brightness Down: Ctrl + Shift + ↓ - -💡 Features: -• Click-through overlay - won't interfere with your work -• Global hotkeys work from any application -• Right-click taskbar icon for full menu -• Control toolbar with brightness, color temp, and monitor options -• Color temperature controls (🔥 warmer, ❄️ cooler) -• Switch between monitors or show on all monitors -• Exclude from screen capture (🎥) - invisible in Teams/Zoom sharing - -Created by Scott Hanselman -Version {version}"; - - System.Windows.MessageBox.Show(helpMessage, "Windows Edge Light - Help", - MessageBoxButton.OK, MessageBoxImage.Information); - } - - private void SetupWindow() - { - // Initialize available monitors on first setup - if (availableMonitors.Length == 0) - { - availableMonitors = Screen.AllScreens; - - // Find the primary monitor index - for (int i = 0; i < availableMonitors.Length; i++) - { - if (availableMonitors[i].Primary) - { - currentMonitorIndex = i; - break; - } - } - } - - var targetScreen = availableMonitors.Length > 0 ? availableMonitors[currentMonitorIndex] : Screen.PrimaryScreen; - if (targetScreen == null) return; - - SetupWindowForScreen(targetScreen); - } - - private void SetupWindowForScreen(Screen screen) - { - // Use WorkingArea instead of Bounds to exclude taskbar - var workingArea = screen.WorkingArea; - - // Get DPI scale factor for the target screen - (_dpiScaleX, _dpiScaleY) = GetDpiForScreen(screen); - - // Convert physical pixels to WPF DIPs - this.Left = workingArea.X / _dpiScaleX; - this.Top = workingArea.Y / _dpiScaleY; - this.Width = workingArea.Width / _dpiScaleX; - this.Height = workingArea.Height / _dpiScaleY; - this.WindowState = System.Windows.WindowState.Normal; - } - - private void Window_Loaded(object sender, RoutedEventArgs e) - { - SetupWindow(); - CreateFrameGeometry(); - CreateControlWindow(); - - var hwnd = new WindowInteropHelper(this).Handle; - int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); - SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT | WS_EX_LAYERED); - - RegisterGlobalHotKeys(hwnd); - - // Hook into Windows message processing - HwndSource source = HwndSource.FromHwnd(hwnd); - source.AddHook(HwndHook); - - // Listen for window size/location changes (docking/undocking) - this.SizeChanged += Window_SizeChanged; - this.LocationChanged += Window_LocationChanged; - - // Apply exclude from capture setting - ApplyExcludeFromCapture(); - - // Apply persisted brightness and color temperature - EdgeLightBorder.Opacity = currentOpacity; - SetColorTemperature(_colorTemperature); - - // Apply persisted on/off state - if (!isLightOn) - { - EdgeLightBorder.Visibility = Visibility.Collapsed; - } - - InstallMouseHook(); - } - - private void RegisterGlobalHotKeys(IntPtr hwnd) - { - var failedHotKeys = new List(); - - if (!RegisterHotKey(hwnd, HOTKEY_TOGGLE, MOD_CONTROL | MOD_SHIFT, VK_L)) - { - failedHotKeys.Add("Toggle Light (Ctrl+Shift+L)"); - } - - if (!RegisterHotKey(hwnd, HOTKEY_BRIGHTNESS_UP, MOD_CONTROL | MOD_SHIFT, VK_UP)) - { - failedHotKeys.Add("Brightness Up (Ctrl+Shift+Up)"); - } - - if (!RegisterHotKey(hwnd, HOTKEY_BRIGHTNESS_DOWN, MOD_CONTROL | MOD_SHIFT, VK_DOWN)) - { - failedHotKeys.Add("Brightness Down (Ctrl+Shift+Down)"); - } - - if (failedHotKeys.Count > 0) - { - notifyIcon?.ShowBalloonTip( - 5000, - "Windows Edge Light hotkey conflict", - "Some keyboard shortcuts could not be registered because another app is using them:\n\n" + - string.Join("\n", failedHotKeys) + - "\n\nUse the tray menu controls instead.", - ToolTipIcon.Warning); - } - } - - private void InstallMouseHook() - { - // Store callback to prevent garbage collection - mouseHookCallback = MouseHookProc; - - using var curProcess = System.Diagnostics.Process.GetCurrentProcess(); - using var curModule = curProcess.MainModule; - if (curModule != null) - { - mouseHookHandle = SetWindowsHookEx(WH_MOUSE_LL, mouseHookCallback, - GetModuleHandle(curModule.ModuleName), 0); - } - } - - private void UninstallMouseHook() - { - if (mouseHookHandle != IntPtr.Zero) - { - UnhookWindowsHookEx(mouseHookHandle); - mouseHookHandle = IntPtr.Zero; - } - } - - private IntPtr MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) - { - if (nCode >= 0 && wParam == (IntPtr)WM_MOUSEMOVE) - { - var hookStruct = Marshal.PtrToStructure(lParam); - - // Dispatch to UI thread for WPF operations - Dispatcher.BeginInvoke(new Action(() => - { - HandleMouseMove(hookStruct.pt.x, hookStruct.pt.y); - }), System.Windows.Threading.DispatcherPriority.Input); - } - - return CallNextHookEx(mouseHookHandle, nCode, wParam, lParam); - } - - private void HandleMouseMove(int screenX, int screenY) - { - if (!isLightOn) - { - if (EdgeLightBorder.Visibility != Visibility.Collapsed) - { - EdgeLightBorder.Visibility = Visibility.Collapsed; - } - - if (hoverCursorRing != null && hoverCursorRing.Visibility != Visibility.Collapsed) - { - hoverCursorRing.Visibility = Visibility.Collapsed; - } - // Restore original geometry if previously punched - if (baseFrameGeometry != null && EdgeLightBorder.Data != baseFrameGeometry) - { - EdgeLightBorder.Data = baseFrameGeometry; - } - - // Also handle additional windows - foreach (var ctx in additionalMonitorWindows) - { - if (ctx.BorderPath.Visibility != Visibility.Collapsed) - ctx.BorderPath.Visibility = Visibility.Collapsed; - if (ctx.HoverRing.Visibility != Visibility.Collapsed) - ctx.HoverRing.Visibility = Visibility.Collapsed; - if (ctx.BorderPath.Data != ctx.BaseGeometry) - ctx.BorderPath.Data = ctx.BaseGeometry; - } - - return; - } - - // --- Main Window Logic --- - if (frameOuterRect != null && frameInnerRect != null && hoverCursorRing != null && baseFrameGeometry != null) - { - var screen = availableMonitors.Length > 0 ? availableMonitors[currentMonitorIndex] : Screen.PrimaryScreen; - if (screen != null) - { - ApplyHolePunchEffect( - screenX, screenY, - screen, - _dpiScaleX, _dpiScaleY, - frameOuterRect.Value, frameInnerRect.Value, - hoverCursorRing, - EdgeLightBorder, - baseFrameGeometry, - pathOffsetX, pathOffsetY, - (ring, x, y) => { Canvas.SetLeft(ring, x); Canvas.SetTop(ring, y); } - ); - } - } - - // --- Additional Windows Logic --- - foreach (var ctx in additionalMonitorWindows) - { - try - { - ApplyHolePunchEffect( - screenX, screenY, - ctx.Screen, - ctx.DpiScaleX, ctx.DpiScaleY, - ctx.FrameOuterRect, ctx.FrameInnerRect, - ctx.HoverRing, - ctx.BorderPath, - ctx.BaseGeometry, - ctx.PathOffsetX, ctx.PathOffsetY, - (ring, x, y) => { ring.Margin = new Thickness(x, y, 0, 0); } - ); - } - catch (InvalidOperationException) - { - // Can happen if window is closing or not ready - } - } - } - - private void ApplyHolePunchEffect( - int screenX, int screenY, - Screen screen, - double dpiScaleX, double dpiScaleY, - Rect frameOuterRect, Rect frameInnerRect, - Ellipse hoverRing, - System.Windows.Shapes.Path borderPath, - Geometry baseGeometry, - double pathOffsetX, double pathOffsetY, - Action positionRing) - { - // Manual coordinate calculation to avoid PointFromScreen issues across monitors/DPIs - // We positioned the window using dpiScaleX/Y relative to the screen WorkingArea. - double relX = (screenX - screen.WorkingArea.X) / dpiScaleX; - double relY = (screenY - screen.WorkingArea.Y) / dpiScaleY; - var windowPt = new System.Windows.Point(relX, relY); - - // Existing frame band detection (outer minus inner) - bool inFrameBand = frameOuterRect.Contains(windowPt) && !frameInnerRect.Contains(windowPt); - - // Early detection zone just inside the inner edge: a band with thickness = hole radius (cursor ring radius) - double ringDiameter = hoverRing.Width; - double holeRadius = ringDiameter / 2; // match ring size - var innerProximityRect = new Rect( - frameInnerRect.X + holeRadius, - frameInnerRect.Y + holeRadius, - frameInnerRect.Width - (holeRadius * 2), - frameInnerRect.Height - (holeRadius * 2)); - - // Near from inside means inside innerRect but within holeRadius of its edge (i.e., not deep inside innerProximityRect) - bool nearFromInside = frameInnerRect.Contains(windowPt) && !innerProximityRect.Contains(windowPt); - - bool overFrame = inFrameBand || nearFromInside; - - if (overFrame) - { - positionRing(hoverRing, windowPt.X - ringDiameter / 2, windowPt.Y - ringDiameter / 2); - - if (hoverRing.Visibility != Visibility.Visible) - { - hoverRing.Visibility = Visibility.Visible; - } - - // Punch a transparent hole under the ring by excluding a circle geometry from the frame - // Convert window coordinates to geometry local coordinates by subtracting stored offsets - var localCenter = new System.Windows.Point(windowPt.X - pathOffsetX, windowPt.Y - pathOffsetY); - var hole = new EllipseGeometry(localCenter, holeRadius, holeRadius); - borderPath.Data = new CombinedGeometry(GeometryCombineMode.Exclude, baseGeometry, hole); - } - else - { - if (hoverRing.Visibility != Visibility.Collapsed) - { - hoverRing.Visibility = Visibility.Collapsed; - } - - if (borderPath.Visibility != Visibility.Visible) - { - borderPath.Visibility = Visibility.Visible; - } - // Restore original geometry (remove hole) - if (baseGeometry != null && borderPath.Data != baseGeometry) - { - borderPath.Data = baseGeometry; - } - } - } - - private void CreateControlWindow() - { - controlWindow = new ControlWindow(this); - RepositionControlWindow(); - - // Only show if controls are supposed to be visible - if (isControlWindowVisible) - { - controlWindow.Show(); - } - } - - private void CreateFrameGeometry() - { - // Get actual dimensions (accounting for margin) - double width = this.ActualWidth - 40; // 20px margin on each side - double height = this.ActualHeight - 40; - - const double frameThickness = 80; - const double outerRadius = 100; // Extra rounded like macOS - const double innerRadius = 60; // Keep proportional - - // Outer rounded rectangle - var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); - - // Inner rounded rectangle - var innerRect = new RectangleGeometry( - new Rect(frameThickness, frameThickness, - width - (frameThickness * 2), - height - (frameThickness * 2)), - innerRadius, innerRadius); - - // Combine: outer minus inner = frame - var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); - baseFrameGeometry = frameGeometry; // store original - EdgeLightBorder.Data = frameGeometry; - pathOffsetX = (ActualWidth - width) / 2.0; // store offsets for local coordinate conversion - pathOffsetY = (ActualHeight - height) / 2.0; - // Expand outer and contract inner rects for earlier hover detection based on ring hole radius. - double ringDiameter = hoverCursorRing?.Width ?? 0; - double holeRadius = ringDiameter / 2.0; - frameOuterRect = new Rect(pathOffsetX - holeRadius, pathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); - frameInnerRect = new Rect(pathOffsetX + frameThickness + holeRadius, pathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); - } - - private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) - { - const int WM_HOTKEY = 0x0312; - - if (msg == WM_HOTKEY) - { - int hotkeyId = wParam.ToInt32(); - - switch (hotkeyId) - { - case HOTKEY_TOGGLE: - ToggleLight(); - handled = true; - break; - case HOTKEY_BRIGHTNESS_UP: - IncreaseBrightness(); - handled = true; - break; - case HOTKEY_BRIGHTNESS_DOWN: - DecreaseBrightness(); - handled = true; - break; - } - } - - return IntPtr.Zero; - } - - protected override void OnDpiChanged(DpiScale oldDpi, DpiScale newDpi) - { - base.OnDpiChanged(oldDpi, newDpi); - - _dpiScaleX = newDpi.DpiScaleX; - _dpiScaleY = newDpi.DpiScaleY; - - // Ensure window covers the current monitor correctly with new DPI - if (availableMonitors.Length > 0) - { - // Re-verify which monitor we are on, as we might have just moved - UpdateCurrentMonitorIndex(); - - if (currentMonitorIndex < availableMonitors.Length) - { - var screen = availableMonitors[currentMonitorIndex]; - var workingArea = screen.WorkingArea; - - // Only update if significantly different to avoid loops - double newLeft = workingArea.X / _dpiScaleX; - double newTop = workingArea.Y / _dpiScaleY; - double newWidth = workingArea.Width / _dpiScaleX; - double newHeight = workingArea.Height / _dpiScaleY; - - if (Math.Abs(this.Left - newLeft) > 1 || Math.Abs(this.Top - newTop) > 1 || - Math.Abs(this.Width - newWidth) > 1 || Math.Abs(this.Height - newHeight) > 1) - { - this.Left = newLeft; - this.Top = newTop; - this.Width = newWidth; - this.Height = newHeight; - } - } - } - } - - protected override void OnClosed(EventArgs e) - { - UninstallMouseHook(); - - var hwnd = new WindowInteropHelper(this).Handle; - UnregisterHotKey(hwnd, HOTKEY_TOGGLE); - UnregisterHotKey(hwnd, HOTKEY_BRIGHTNESS_UP); - UnregisterHotKey(hwnd, HOTKEY_BRIGHTNESS_DOWN); - - if (notifyIcon != null) - { - notifyIcon.Visible = false; - notifyIcon.Dispose(); - } - - HideAdditionalMonitorWindows(); - controlWindow?.Close(); - - base.OnClosed(e); - } - - private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) - { - if (e.Key == Key.L && - (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && - (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) - { - ToggleLight(); - } - else if (e.Key == Key.Escape) - { - System.Windows.Application.Current.Shutdown(); - } - } - - private void Toggle_Click(object sender, RoutedEventArgs e) - { - ToggleLight(); - } - - private void ToggleLight() - { - isLightOn = !isLightOn; - if (isLightOn) - { - EdgeLightBorder.Visibility = Visibility.Visible; - // Restore base geometry on toggle if needed - if (baseFrameGeometry != null) - { - EdgeLightBorder.Data = baseFrameGeometry; - } - } - else - { - EdgeLightBorder.Visibility = Visibility.Collapsed; - if (hoverCursorRing != null) - { - hoverCursorRing.Visibility = Visibility.Collapsed; - } - } - - // Update all additional monitor windows - UpdateAdditionalMonitorWindows(); - - settings.IsLightOn = isLightOn; - settings.Save(); - } - - public void HandleToggle() - { - ToggleLight(); - } - - public void ToggleControlsVisibility() - { - isControlWindowVisible = !isControlWindowVisible; - - // Apply visibility change if control window exists - if (controlWindow != null) - { - if (isControlWindowVisible) - { - controlWindow.Show(); - } - else - { - controlWindow.Hide(); - } - } - // Note: If controlWindow doesn't exist yet, isControlWindowVisible state - // is preserved and will be applied when CreateControlWindow() is called - - UpdateTrayMenuToggleControlsText(); - } - - private void UpdateTrayMenuToggleControlsText() - { - if (toggleControlsMenuItem != null) - { - toggleControlsMenuItem.Text = isControlWindowVisible ? "🎛️ Hide Controls" : "🎛️ Show Controls"; - } - } - - public void ToggleExcludeFromCapture() - { - settings.ExcludeFromCapture = !settings.ExcludeFromCapture; - settings.Save(); - - // Update menu checkmark - if (excludeFromCaptureMenuItem != null) - { - excludeFromCaptureMenuItem.Checked = settings.ExcludeFromCapture; - } - - // Apply the setting to all windows - ApplyExcludeFromCapture(); - } - - private void ApplyExcludeFromCapture() - { - var hwnd = new WindowInteropHelper(this).Handle; - if (hwnd != IntPtr.Zero) - { - var result = SetWindowDisplayAffinity(hwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); - if (!result) - { - var error = Marshal.GetLastWin32Error(); - System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for main window. Error: {error}"); - } - } - - // Apply to control window - if (controlWindow != null) - { - var controlHwnd = new WindowInteropHelper(controlWindow).Handle; - if (controlHwnd != IntPtr.Zero) - { - var result = SetWindowDisplayAffinity(controlHwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); - if (!result) - { - var error = Marshal.GetLastWin32Error(); - System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for control window. Error: {error}"); - } - } - } - - // Apply to all additional monitor windows - foreach (var ctx in additionalMonitorWindows) - { - var monitorHwnd = new WindowInteropHelper(ctx.Window).Handle; - if (monitorHwnd != IntPtr.Zero) - { - var result = SetWindowDisplayAffinity(monitorHwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); - if (!result) - { - var error = Marshal.GetLastWin32Error(); - System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for monitor window. Error: {error}"); - } - } - } - } - - public void IncreaseBrightness() - { - SetBrightness(currentOpacity + OpacityStep); - } - - public void DecreaseBrightness() - { - SetBrightness(currentOpacity - OpacityStep); - } - - public void SetBrightness(double value, bool save = true) - { - currentOpacity = Math.Max(MinOpacity, Math.Min(MaxOpacity, value)); - EdgeLightBorder.Opacity = currentOpacity; - UpdateAdditionalMonitorWindows(); - - if (save) - { - settings.Brightness = currentOpacity; - settings.Save(); - } - } - - private void UpdateAdditionalMonitorWindows() - { - foreach (var ctx in additionalMonitorWindows) - { - var path = ctx.BorderPath; - path.Opacity = currentOpacity; - path.Visibility = isLightOn ? Visibility.Visible : Visibility.Collapsed; - - // Update color temperature - if (path.Fill is LinearGradientBrush brush && brush.GradientStops.Count >= 3) - { - var cool = System.Windows.Media.Color.FromRgb(220, 235, 255); - var warm = System.Windows.Media.Color.FromRgb(255, 220, 180); - - System.Windows.Media.Color Lerp(System.Windows.Media.Color a, System.Windows.Media.Color b, double t) - { - byte LerpByte(byte x, byte y, double tt) => (byte)(x + (y - x) * tt); - return System.Windows.Media.Color.FromArgb(255, LerpByte(a.R, b.R, t), LerpByte(a.G, b.G, t), LerpByte(a.B, b.B, t)); - } - - var midColor = Lerp(cool, warm, _colorTemperature); - - foreach (var stop in brush.GradientStops) - { - if (stop.Offset is > 0.2 and < 0.8) - { - stop.Color = midColor; - } - } - } - } - } - - public void IncreaseColorTemperature() - { - SetColorTemperature(_colorTemperature + ColorTempStep); - } - - public void DecreaseColorTemperature() - { - SetColorTemperature(_colorTemperature - ColorTempStep); - } - - public void SetColorTemperature(double value, bool save = true) - { - _colorTemperature = Math.Max(MinColorTemp, Math.Min(MaxColorTemp, value)); - - // Map 0-1 slider to a simple cool-to-warm gradient. - // We'll bias the inner gradient stops from blueish-white (cool) to amber (warm). - // NOTE: This assumes the brush defined in XAML is still a LinearGradientBrush. - if (EdgeLightBorder.Fill is LinearGradientBrush brush && brush.GradientStops.Count >= 3) - { - // Cool: RGB ~ (220, 235, 255), Warm: RGB ~ (255, 220, 180) - System.Windows.Media.Color Lerp(System.Windows.Media.Color a, System.Windows.Media.Color b, double t) - { - byte LerpByte(byte x, byte y, double tt) => (byte)(x + (y - x) * tt); - - return System.Windows.Media.Color.FromArgb( - 255, - LerpByte(a.R, b.R, t), - LerpByte(a.G, b.G, t), - LerpByte(a.B, b.B, t)); - } - - var cool = System.Windows.Media.Color.FromRgb(220, 235, 255); - var warm = System.Windows.Media.Color.FromRgb(255, 220, 180); - - var midColor = Lerp(cool, warm, _colorTemperature); - - // Update a couple of inner stops to shift perceived temperature - // Keep outer rim relatively neutral for consistent edge. - foreach (var stop in brush.GradientStops) - { - if (stop.Offset is > 0.2 and < 0.8) - { - stop.Color = midColor; - } - } - } - - // Update all additional monitor windows - UpdateAdditionalMonitorWindows(); - - if (save) - { - settings.ColorTemperature = _colorTemperature; - settings.Save(); - } - } - - public void MoveToNextMonitor() - { - // If in all monitors mode, do nothing - if (showOnAllMonitors) return; - - // Refresh monitor list in case of hot-plug/unplug - availableMonitors = Screen.AllScreens; - - if (availableMonitors.Length <= 1) - { - return; - } - - // Ensure currentMonitorIndex is accurate before moving - UpdateCurrentMonitorIndex(); - - _isManualMonitorSwitch = true; - try - { - // Cycle to next monitor - currentMonitorIndex = (currentMonitorIndex + 1) % availableMonitors.Length; - var targetScreen = availableMonitors[currentMonitorIndex]; - - // Reposition main window to new monitor using physical coordinates to trigger DPI change correctly - var hwnd = new WindowInteropHelper(this).Handle; - SetWindowPos(hwnd, IntPtr.Zero, - targetScreen.WorkingArea.X, targetScreen.WorkingArea.Y, - targetScreen.WorkingArea.Width, targetScreen.WorkingArea.Height, - SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); - - // Force a size update if DPI didn't change (SetWindowPos might not trigger OnDpiChanged) - // If DPI changed, OnDpiChanged will handle it. - // But we can't easily know if OnDpiChanged fired yet. - // However, setting properties to the same value is cheap in WPF. - // We need to ensure we use the NEW DPI if it changed. - // OnDpiChanged updates _dpiScaleX/Y. - - // If we are on the same thread, OnDpiChanged (via WM_DPICHANGED) should have fired synchronously during SetWindowPos. - // So _dpiScaleX/Y should be up to date. - - double newLeft = targetScreen.WorkingArea.X / _dpiScaleX; - double newTop = targetScreen.WorkingArea.Y / _dpiScaleY; - double newWidth = targetScreen.WorkingArea.Width / _dpiScaleX; - double newHeight = targetScreen.WorkingArea.Height / _dpiScaleY; - - this.Left = newLeft; - this.Top = newTop; - this.Width = newWidth; - this.Height = newHeight; - } - finally - { - _isManualMonitorSwitch = false; - } - - // Reposition control window to follow - RepositionControlWindow(); - } - - [DllImport("user32.dll", SetLastError = true)] - private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); - private const uint SWP_NOZORDER = 0x0004; - private const uint SWP_NOACTIVATE = 0x0010; - private const uint SWP_FRAMECHANGED = 0x0020; - - public void ToggleAllMonitors() - { - showOnAllMonitors = !showOnAllMonitors; - - if (showOnAllMonitors) - { - ShowOnAllMonitors(); - } - else - { - HideAdditionalMonitorWindows(); - } - - controlWindow?.UpdateAllMonitorsButtonState(); - } - - private void ShowOnAllMonitors() - { - // Refresh monitor list - availableMonitors = Screen.AllScreens; - - // Close any existing additional windows - HideAdditionalMonitorWindows(); - - // Create a window for each monitor except the current one (this window) - for (int i = 0; i < availableMonitors.Length; i++) - { - if (i != currentMonitorIndex) - { - var monitorCtx = CreateMonitorWindow(availableMonitors[i]); - additionalMonitorWindows.Add(monitorCtx); - monitorCtx.Window.Show(); - } - } - } - - private void HideAdditionalMonitorWindows() - { - foreach (var ctx in additionalMonitorWindows) - { - ctx.Window.Close(); - } - additionalMonitorWindows.Clear(); - } - - private MonitorWindowContext CreateMonitorWindow(Screen screen) - { - var window = new Window - { - Title = "Windows Edge Light", - AllowsTransparency = true, - Background = System.Windows.Media.Brushes.Transparent, - ResizeMode = ResizeMode.NoResize, - ShowInTaskbar = false, - Topmost = true, - WindowStyle = WindowStyle.None - }; - - // Position on the target screen - var workingArea = screen.WorkingArea; - - // Get the correct DPI scale for THIS specific screen - var (screenDpiX, screenDpiY) = GetDpiForScreen(screen); - - // Convert physical pixels to WPF DIPs using the correct per-monitor DPI - window.Left = workingArea.X / screenDpiX; - window.Top = workingArea.Y / screenDpiY; - window.Width = workingArea.Width / screenDpiX; - window.Height = workingArea.Height / screenDpiY; - - // Create the grid and edge light border - var grid = new System.Windows.Controls.Grid { IsHitTestVisible = false }; - var path = new System.Windows.Shapes.Path - { - HorizontalAlignment = System.Windows.HorizontalAlignment.Center, - VerticalAlignment = System.Windows.VerticalAlignment.Center, - Stretch = System.Windows.Media.Stretch.None, - Opacity = currentOpacity, - Visibility = isLightOn ? Visibility.Visible : Visibility.Collapsed - }; - - // Create gradient brush - var gradient = new LinearGradientBrush - { - StartPoint = new System.Windows.Point(0, 0), - EndPoint = new System.Windows.Point(1, 1) - }; - gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 0.0)); - gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(240, 240, 240), 0.3)); - gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 0.5)); - gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(240, 240, 240), 0.7)); - gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 1.0)); - path.Fill = gradient; - - // Add drop shadow effect - path.Effect = new System.Windows.Media.Effects.DropShadowEffect - { - BlurRadius = 76, - Opacity = 1, - ShadowDepth = 0, - Color = System.Windows.Media.Color.FromRgb(255, 255, 255) - }; - - // Create hover ring (Ellipse) - var hoverRing = new Ellipse - { - Width = 140, - Height = 140, - Fill = System.Windows.Media.Brushes.Transparent, - Visibility = Visibility.Collapsed, - HorizontalAlignment = System.Windows.HorizontalAlignment.Left, - VerticalAlignment = System.Windows.VerticalAlignment.Top - }; - // Add drop shadow to ring - actually main window doesn't seem to have this on the ring itself? - // Main window XAML doesn't show effect on HoverCursorRing. - // So removing effect to match. - - // Create frame geometry - double width = window.Width - 40; - double height = window.Height - 40; - const double frameThickness = 80; - const double outerRadius = 100; - const double innerRadius = 60; - - var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); - var innerRect = new RectangleGeometry( - new Rect(frameThickness, frameThickness, - width - (frameThickness * 2), - height - (frameThickness * 2)), - innerRadius, innerRadius); - - var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); - path.Data = frameGeometry; - - grid.Children.Add(path); - grid.Children.Add(hoverRing); - window.Content = grid; - - // Calculate geometry data for hole punch - double pathOffsetX = (window.Width - width) / 2.0; - double pathOffsetY = (window.Height - height) / 2.0; - - double ringDiameter = hoverRing.Width; - double holeRadius = ringDiameter / 2.0; - var frameOuterRect = new Rect(pathOffsetX - holeRadius, pathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); - var frameInnerRect = new Rect(pathOffsetX + frameThickness + holeRadius, pathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); - - var ctx = new MonitorWindowContext - { - Window = window, - Screen = screen, - BorderPath = path, - HoverRing = hoverRing, - BaseGeometry = frameGeometry, - FrameOuterRect = frameOuterRect, - FrameInnerRect = frameInnerRect, - PathOffsetX = pathOffsetX, - PathOffsetY = pathOffsetY, - DpiScaleX = screenDpiX, // Use calculated DPI for this screen - DpiScaleY = screenDpiY - }; - - // Make window click-through and handle DPI - window.Loaded += (s, e) => - { - var hwnd = new WindowInteropHelper(window).Handle; - int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); - SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT | WS_EX_LAYERED); - - // Apply exclude from capture setting - var result = SetWindowDisplayAffinity(hwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); - if (!result) - { - var error = Marshal.GetLastWin32Error(); - System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for monitor window during creation. Error: {error}"); - } - - // Verify and update DPI if WPF reports a different value after window is loaded - var source = PresentationSource.FromVisual(window); - if (source != null) - { - double dpiX = source.CompositionTarget.TransformToDevice.M11; - double dpiY = source.CompositionTarget.TransformToDevice.M22; - - // Only reposition if DPI changed significantly from our initial calculation - if (Math.Abs(dpiX - ctx.DpiScaleX) > 0.01 || Math.Abs(dpiY - ctx.DpiScaleY) > 0.01) - { - ctx.DpiScaleX = dpiX; - ctx.DpiScaleY = dpiY; - - // Reposition/Resize with correct DPI - window.Left = screen.WorkingArea.X / dpiX; - window.Top = screen.WorkingArea.Y / dpiY; - window.Width = screen.WorkingArea.Width / dpiX; - window.Height = screen.WorkingArea.Height / dpiY; - - // Recalculate geometry for new window size - UpdateMonitorGeometry(ctx); - } - } - }; - - window.DpiChanged += (s, dpiArgs) => - { - ctx.DpiScaleX = dpiArgs.NewDpi.DpiScaleX; - ctx.DpiScaleY = dpiArgs.NewDpi.DpiScaleY; - - window.Left = screen.WorkingArea.X / ctx.DpiScaleX; - window.Top = screen.WorkingArea.Y / ctx.DpiScaleY; - window.Width = screen.WorkingArea.Width / ctx.DpiScaleX; - window.Height = screen.WorkingArea.Height / ctx.DpiScaleY; - - UpdateMonitorGeometry(ctx); - }; - - return ctx; - } - - private void UpdateMonitorGeometry(MonitorWindowContext ctx) - { - double width = ctx.Window.Width - 40; - double height = ctx.Window.Height - 40; - const double frameThickness = 80; - const double outerRadius = 100; - const double innerRadius = 60; - - var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); - var innerRect = new RectangleGeometry( - new Rect(frameThickness, frameThickness, - width - (frameThickness * 2), - height - (frameThickness * 2)), - innerRadius, innerRadius); - - var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); - - ctx.BaseGeometry = frameGeometry; - ctx.BorderPath.Data = frameGeometry; - - ctx.PathOffsetX = (ctx.Window.Width - width) / 2.0; - ctx.PathOffsetY = (ctx.Window.Height - height) / 2.0; - - double ringDiameter = ctx.HoverRing.Width; - double holeRadius = ringDiameter / 2.0; - - ctx.FrameOuterRect = new Rect(ctx.PathOffsetX - holeRadius, ctx.PathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); - ctx.FrameInnerRect = new Rect(ctx.PathOffsetX + frameThickness + holeRadius, ctx.PathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); - } - - public bool IsShowingOnAllMonitors() - { - return showOnAllMonitors; - } - - private void RepositionControlWindow() - { - if (controlWindow == null) return; - - // Respect a user-dragged position for the current session. - if (controlWindowManuallyMoved) return; - - // Position at bottom center of main window - controlWindow.Left = this.Left + (this.Width - controlWindow.Width) / 2; - controlWindow.Top = this.Top + this.Height - controlWindow.Height - 124; - } - - public void NotifyControlWindowManuallyMoved() - { - controlWindowManuallyMoved = true; - } - - public void ResetControlWindowPosition() - { - controlWindowManuallyMoved = false; - RepositionControlWindow(); - } - - public bool HasMultipleMonitors() - { - // Refresh monitor count to handle hot-plug scenarios - availableMonitors = Screen.AllScreens; - return availableMonitors.Length > 1; - } - - public bool IsExcludeFromCaptureEnabled() - { - return settings.ExcludeFromCapture; - } - - public double GetBrightness() => currentOpacity; - - public double GetColorTemperature() => _colorTemperature; - - public bool GetIsToggleButtonVisible() => settings.ShowToggleButton; - - public bool GetIsBrightnessButtonsVisible() => settings.ShowBrightnessButtons; - - public bool GetIsColorTempButtonsVisible() => settings.ShowColorTempButtons; - - public bool GetIsControlMonitorsButtonVisible() => settings.ShowMonitorControlButtons; - - public void SetIsToggleVisible(bool isVisible) - { - settings.ShowToggleButton = isVisible; - settings.Save(); - } - - public void SetIsBrightnessButtonsVisible(bool isVisible) - { - settings.ShowBrightnessButtons = isVisible; - settings.Save(); - } - - public void SetIsColorTempButtonsVisible(bool isVisible) - { - settings.ShowColorTempButtons = isVisible; - settings.Save(); - } - - public void SetIsControlMonitorsButtonVisible(bool isVisible) - { - settings.ShowMonitorControlButtons = isVisible; - settings.Save(); - } - - private void Window_SizeChanged(object sender, SizeChangedEventArgs e) - { - // Recreate geometry when window size changes (e.g., different monitor resolution) - if (EdgeLightBorder != null) - { - CreateFrameGeometry(); - } - - // Reposition control window - RepositionControlWindow(); - - // Update which monitor we're actually on - UpdateCurrentMonitorIndex(); - } - - private void Window_LocationChanged(object? sender, EventArgs e) - { - // Reposition control window when main window moves - RepositionControlWindow(); - - // Update which monitor we're actually on - UpdateCurrentMonitorIndex(); - } - - private void UpdateCurrentMonitorIndex() - { - // If we are manually switching, trust the index we set explicitly - if (_isManualMonitorSwitch) return; - - // Refresh monitor list - availableMonitors = Screen.AllScreens; - - if (availableMonitors.Length == 0) return; - - try - { - // Use PointToScreen to get accurate physical coordinates of the window center - // This handles DPI scaling correctly unlike manual calculation - var centerPoint = this.PointToScreen(new System.Windows.Point(this.ActualWidth / 2, this.ActualHeight / 2)); - var drawingPoint = new System.Drawing.Point((int)centerPoint.X, (int)centerPoint.Y); - - for (int i = 0; i < availableMonitors.Length; i++) - { - if (availableMonitors[i].Bounds.Contains(drawingPoint)) - { - currentMonitorIndex = i; - break; - } - } - } - catch (InvalidOperationException) - { - // Window might not be loaded or visible yet - } - } - - private (double dpiScaleX, double dpiScaleY) GetDpiForScreen(Screen screen) - { - try - { - // Get monitor handle for the center of the screen - var centerPoint = new POINT - { - x = screen.Bounds.X + screen.Bounds.Width / 2, - y = screen.Bounds.Y + screen.Bounds.Height / 2 - }; - - IntPtr hMonitor = MonitorFromPoint(centerPoint, MONITOR_DEFAULTTONEAREST); - - if (hMonitor != IntPtr.Zero) - { - int result = GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, out uint dpiX, out uint dpiY); - if (result == 0) // S_OK - { - // Convert from DPI to scale factor (96 DPI = 100% = 1.0) - return (dpiX / 96.0, dpiY / 96.0); - } - } - } - catch - { - // Fall through to default - } - - // Fallback: return 1.0 (100% scaling) - return (1.0, 1.0); - } - - private void BrightnessUp_Click(object sender, RoutedEventArgs e) - { - IncreaseBrightness(); - } - - private void BrightnessDown_Click(object sender, RoutedEventArgs e) - { - DecreaseBrightness(); - } - - private void Close_Click(object sender, RoutedEventArgs e) - { - System.Windows.Application.Current.Shutdown(); - } - - private const int GWL_EXSTYLE = -20; - private const int WS_EX_TRANSPARENT = 0x00000020; - private const int WS_EX_LAYERED = 0x00080000; - - [DllImport("user32.dll")] - private static extern int GetWindowLong(IntPtr hwnd, int index); - - [DllImport("user32.dll")] - private static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle); +using System.IO; +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Media.Effects; +using System.Windows.Shapes; +using System.Windows.Threading; +using MediaColor = System.Windows.Media.Color; + +namespace WindowsEdgeLight; + +public partial class MainWindow : Window +{ + private bool isLightOn = true; + private double currentOpacity = 1.0; // Full brightness by default + private const double OpacityStep = 0.15; + private const double MinOpacity = 0.2; + private const double MaxOpacity = 1.0; + + + // Color temperature ("cool" blue-ish to "warm" amber-ish) + // We'll model this as a simple 0-1 slider where 0 = coolest, 1 = warmest. + private double _colorTemperature = 0.5; + private const double ColorTempStep = 0.1; + private const double MinColorTemp = 0.0; + private const double MaxColorTemp = 1.0; + + // DPI Scale + private double _dpiScaleX = 1.0; + private double _dpiScaleY = 1.0; + + private bool _isManualMonitorSwitch = false; + + private NotifyIcon? notifyIcon; + private ControlWindow? controlWindow; + // Tracks whether the control window should be visible (controls initial visibility and toggle state) + private bool isControlWindowVisible = true; + // Session-only: once the user drags the control toolbar, stop auto-repositioning it. + private bool controlWindowManuallyMoved = false; + private ToolStripMenuItem? toggleControlsMenuItem; + private ToolStripMenuItem? excludeFromCaptureMenuItem; + + // Application settings + private AppSettings settings = new AppSettings(); + + private sealed class HoleCache + { + public Geometry? BaseGeometry { get; set; } + public EllipseGeometry? Hole { get; set; } + public CombinedGeometry? Combined { get; set; } + } + + private class MonitorWindowContext + { + public Window Window { get; set; } = null!; + public Screen Screen { get; set; } = null!; + public System.Windows.Shapes.Path BorderPath { get; set; } = null!; + public Ellipse HoverRing { get; set; } = null!; + public Geometry BaseGeometry { get; set; } = null!; + public Rect FrameOuterRect { get; set; } + public Rect FrameInnerRect { get; set; } + public double PathOffsetX { get; set; } + public double PathOffsetY { get; set; } + public double DpiScaleX { get; set; } = 1.0; + public double DpiScaleY { get; set; } = 1.0; + public HoleCache HoleCache { get; } = new(); + } + + // Monitor management + private int currentMonitorIndex = 0; + private Screen[] availableMonitors = Array.Empty(); + private bool showOnAllMonitors = false; + private List additionalMonitorWindows = new List(); + + // Global hotkey IDs + private const int HOTKEY_TOGGLE = 1; + private const int HOTKEY_BRIGHTNESS_UP = 2; + private const int HOTKEY_BRIGHTNESS_DOWN = 3; + + [DllImport("user32.dll")] + private static extern int GetSystemMetrics(int nIndex); + private const int SM_CXSCREEN = 0; + private const int SM_CYSCREEN = 1; + + [DllImport("user32.dll")] + private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); + + [DllImport("user32.dll")] + private static extern bool UnregisterHotKey(IntPtr hWnd, int id); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool SetWindowDisplayAffinity(IntPtr hWnd, uint dwAffinity); + + private const uint WDA_NONE = 0x00000000; + private const uint WDA_EXCLUDEFROMCAPTURE = 0x00000011; + + [DllImport("user32.dll")] + private static extern IntPtr MonitorFromPoint(POINT pt, uint dwFlags); + + [DllImport("shcore.dll")] + private static extern int GetDpiForMonitor(IntPtr hmonitor, int dpiType, out uint dpiX, out uint dpiY); + + private const int MDT_EFFECTIVE_DPI = 0; + private const uint MONITOR_DEFAULTTONEAREST = 2; + + [StructLayout(LayoutKind.Sequential)] + private struct POINT + { + public int x; // lowercase to match existing usage + public int y; + } + + // Mouse hook P/Invoke declarations + [DllImport("user32.dll", SetLastError = true)] + private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId); + + [DllImport("user32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool UnhookWindowsHookEx(IntPtr hhk); + + [DllImport("user32.dll")] + private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr GetModuleHandle(string lpModuleName); + + private const int WH_MOUSE_LL = 14; + private const int WM_MOUSEMOVE = 0x0200; + + [StructLayout(LayoutKind.Sequential)] + private struct MSLLHOOKSTRUCT + { + public POINT pt; + public uint mouseData; + public uint flags; + public uint time; + public IntPtr dwExtraInfo; + } + + private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam); + + // Mouse hook management + private IntPtr mouseHookHandle = IntPtr.Zero; + private LowLevelMouseProc? mouseHookCallback; + + private Rect? frameOuterRect; + private Rect? frameInnerRect; + private readonly Ellipse? hoverCursorRing; + // Added fields for hole effect + private Geometry? baseFrameGeometry; // original frame geometry (outer minus inner) + private double pathOffsetX; // offset of geometry within window + private double pathOffsetY; + private readonly HoleCache primaryHoleCache = new(); + + private static readonly MediaColor CoolColor = MediaColor.FromRgb(220, 235, 255); + private static readonly MediaColor WarmColor = MediaColor.FromRgb(255, 220, 180); + + private const uint MOD_CONTROL = 0x0002; + private const uint MOD_SHIFT = 0x0004; + private const uint VK_L = 0x4C; + private const uint VK_UP = 0x26; + private const uint VK_DOWN = 0x28; + + public MainWindow() + { + InitializeComponent(); + hoverCursorRing = FindName("HoverCursorRing") as Ellipse; + + // Load settings + settings = AppSettings.Load(); + + // Restore persisted state + isLightOn = settings.IsLightOn; + currentOpacity = Math.Max(MinOpacity, Math.Min(MaxOpacity, settings.Brightness)); + _colorTemperature = Math.Max(MinColorTemp, Math.Min(MaxColorTemp, settings.ColorTemperature)); + + // Save back if values were clamped + if (currentOpacity != settings.Brightness || _colorTemperature != settings.ColorTemperature) + { + settings.Brightness = currentOpacity; + settings.ColorTemperature = _colorTemperature; + settings.Save(); + } + + SetupNotifyIcon(); + } + + private void SetupNotifyIcon() + { + notifyIcon = new NotifyIcon(); + + // Load icon from embedded resource or file + try + { + var iconPath = System.IO.Path.Combine(AppContext.BaseDirectory, "ringlight_cropped.ico"); + if (File.Exists(iconPath)) + { + notifyIcon.Icon = new System.Drawing.Icon(iconPath); + } + else + { + // Try application icon from exe + var appIcon = System.Drawing.Icon.ExtractAssociatedIcon(Environment.ProcessPath ?? System.Reflection.Assembly.GetExecutingAssembly().Location); + notifyIcon.Icon = appIcon ?? System.Drawing.SystemIcons.Application; + } + } + catch (Exception) + { + // Fallback to default icon if loading fails + notifyIcon.Icon = System.Drawing.SystemIcons.Application; + } + + notifyIcon.Text = "Windows Edge Light - Right-click for options"; + notifyIcon.Visible = true; + + var contextMenu = new ContextMenuStrip(); + contextMenu.Items.Add("📋 Keyboard Shortcuts", null, (s, e) => ShowHelp()); + contextMenu.Items.Add(new ToolStripSeparator()); + contextMenu.Items.Add("💡 Toggle Light (Ctrl+Shift+L)", null, (s, e) => ToggleLight()); + contextMenu.Items.Add("🔆 Brightness Up (Ctrl+Shift+↑)", null, (s, e) => IncreaseBrightness()); + contextMenu.Items.Add("🔅 Brightness Down (Ctrl+Shift+↓)", null, (s, e) => DecreaseBrightness()); + contextMenu.Items.Add(new ToolStripSeparator()); + contextMenu.Items.Add("🔥 K- Warmer Light", null, (s, e) => IncreaseColorTemperature()); + contextMenu.Items.Add("❄️ K+ Cooler Light", null, (s, e) => DecreaseColorTemperature()); + contextMenu.Items.Add(new ToolStripSeparator()); + contextMenu.Items.Add("🖥️ Switch Monitor", null, (s, e) => MoveToNextMonitor()); + contextMenu.Items.Add("🖥️🖥️ Toggle All Monitors", null, (s, e) => ToggleAllMonitors()); + contextMenu.Items.Add(new ToolStripSeparator()); + + // Add toggle controls menu item - text will be set by UpdateTrayMenuToggleControlsText + toggleControlsMenuItem = new ToolStripMenuItem("🎛️ Hide Controls", null, (s, e) => ToggleControlsVisibility()); + contextMenu.Items.Add(toggleControlsMenuItem); + contextMenu.Items.Add("📍 Reset Control Bar Position", null, (s, e) => ResetControlWindowPosition()); + + // Add exclude from capture menu item with checkmark + excludeFromCaptureMenuItem = new ToolStripMenuItem("🎥 Exclude from Screen Capture", null, (s, e) => ToggleExcludeFromCapture()); + excludeFromCaptureMenuItem.CheckOnClick = true; + excludeFromCaptureMenuItem.Checked = settings.ExcludeFromCapture; + contextMenu.Items.Add(excludeFromCaptureMenuItem); + + contextMenu.Items.Add(new ToolStripSeparator()); + contextMenu.Items.Add("✖ Exit", null, (s, e) => System.Windows.Application.Current.Shutdown()); + + notifyIcon.ContextMenuStrip = contextMenu; + notifyIcon.DoubleClick += (s, e) => ShowHelp(); + + // Set initial menu text based on current state + UpdateTrayMenuToggleControlsText(); + } + + private void ShowHelp() + { + var version = System.Reflection.Assembly.GetExecutingAssembly() + .GetName().Version?.ToString() ?? "Unknown"; + + var helpMessage = $@"Windows Edge Light - Keyboard Shortcuts + +💡 Toggle Light: Ctrl + Shift + L +🔆 Brightness Up: Ctrl + Shift + ↑ +🔅 Brightness Down: Ctrl + Shift + ↓ + +💡 Features: +• Click-through overlay - won't interfere with your work +• Global hotkeys work from any application +• Right-click taskbar icon for full menu +• Control toolbar with brightness, color temp, and monitor options +• Color temperature controls (🔥 warmer, ❄️ cooler) +• Switch between monitors or show on all monitors +• Exclude from screen capture (🎥) - invisible in Teams/Zoom sharing + +Created by Scott Hanselman +Version {version}"; + + System.Windows.MessageBox.Show(helpMessage, "Windows Edge Light - Help", + MessageBoxButton.OK, MessageBoxImage.Information); + } + + private void SetupWindow() + { + // Initialize available monitors on first setup + if (availableMonitors.Length == 0) + { + RefreshAvailableMonitors(); + + // Find the primary monitor index + for (int i = 0; i < availableMonitors.Length; i++) + { + if (availableMonitors[i].Primary) + { + currentMonitorIndex = i; + break; + } + } + } + + var targetScreen = GetCurrentScreen(); + if (targetScreen == null) return; + + SetupWindowForScreen(targetScreen); + } + + private void SetupWindowForScreen(Screen screen) + { + // Use WorkingArea instead of Bounds to exclude taskbar + var workingArea = screen.WorkingArea; + + // Get DPI scale factor for the target screen + (_dpiScaleX, _dpiScaleY) = GetDpiForScreen(screen); + + // Convert physical pixels to WPF DIPs + this.Left = workingArea.X / _dpiScaleX; + this.Top = workingArea.Y / _dpiScaleY; + this.Width = workingArea.Width / _dpiScaleX; + this.Height = workingArea.Height / _dpiScaleY; + this.WindowState = System.Windows.WindowState.Normal; + } + + private void Window_Loaded(object sender, RoutedEventArgs e) + { + SetupWindow(); + CreateFrameGeometry(); + CreateControlWindow(); + + var hwnd = new WindowInteropHelper(this).Handle; + int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); + SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT | WS_EX_LAYERED); + + RegisterGlobalHotKeys(hwnd); + + // Hook into Windows message processing + HwndSource source = HwndSource.FromHwnd(hwnd); + source.AddHook(HwndHook); + + // Listen for window size/location changes (docking/undocking) + this.SizeChanged += Window_SizeChanged; + this.LocationChanged += Window_LocationChanged; + + // Apply exclude from capture setting + ApplyExcludeFromCapture(); + + // Apply persisted brightness and color temperature + EdgeLightBorder.Opacity = currentOpacity; + SetColorTemperature(_colorTemperature); + + // Apply persisted on/off state + if (!isLightOn) + { + EdgeLightBorder.Visibility = Visibility.Collapsed; + } + + InstallMouseHook(); + } + + private void RegisterGlobalHotKeys(IntPtr hwnd) + { + var failedHotKeys = new List(); + + if (!RegisterHotKey(hwnd, HOTKEY_TOGGLE, MOD_CONTROL | MOD_SHIFT, VK_L)) + { + failedHotKeys.Add("Toggle Light (Ctrl+Shift+L)"); + } + + if (!RegisterHotKey(hwnd, HOTKEY_BRIGHTNESS_UP, MOD_CONTROL | MOD_SHIFT, VK_UP)) + { + failedHotKeys.Add("Brightness Up (Ctrl+Shift+Up)"); + } + + if (!RegisterHotKey(hwnd, HOTKEY_BRIGHTNESS_DOWN, MOD_CONTROL | MOD_SHIFT, VK_DOWN)) + { + failedHotKeys.Add("Brightness Down (Ctrl+Shift+Down)"); + } + + if (failedHotKeys.Count > 0) + { + notifyIcon?.ShowBalloonTip( + 5000, + "Windows Edge Light hotkey conflict", + "Some keyboard shortcuts could not be registered because another app is using them:\n\n" + + string.Join("\n", failedHotKeys) + + "\n\nUse the tray menu controls instead.", + ToolTipIcon.Warning); + } + } + + private void InstallMouseHook() + { + // Store callback to prevent garbage collection + mouseHookCallback = MouseHookProc; + + using var curProcess = System.Diagnostics.Process.GetCurrentProcess(); + using var curModule = curProcess.MainModule; + if (curModule != null) + { + mouseHookHandle = SetWindowsHookEx(WH_MOUSE_LL, mouseHookCallback, + GetModuleHandle(curModule.ModuleName), 0); + } + } + + private void UninstallMouseHook() + { + if (mouseHookHandle != IntPtr.Zero) + { + UnhookWindowsHookEx(mouseHookHandle); + mouseHookHandle = IntPtr.Zero; + } + } + + private IntPtr MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) + { + if (nCode >= 0 && wParam == (IntPtr)WM_MOUSEMOVE) + { + var hookStruct = Marshal.PtrToStructure(lParam); + + // Dispatch to UI thread for WPF operations + Dispatcher.BeginInvoke(new Action(() => + { + HandleMouseMove(hookStruct.pt.x, hookStruct.pt.y); + }), System.Windows.Threading.DispatcherPriority.Input); + } + + return CallNextHookEx(mouseHookHandle, nCode, wParam, lParam); + } + + private void HandleMouseMove(int screenX, int screenY) + { + if (!isLightOn) + { + if (EdgeLightBorder.Visibility != Visibility.Collapsed) + { + EdgeLightBorder.Visibility = Visibility.Collapsed; + } + + if (hoverCursorRing != null && hoverCursorRing.Visibility != Visibility.Collapsed) + { + hoverCursorRing.Visibility = Visibility.Collapsed; + } + // Restore original geometry if previously punched + if (baseFrameGeometry != null && EdgeLightBorder.Data != baseFrameGeometry) + { + EdgeLightBorder.Data = baseFrameGeometry; + } + + // Also handle additional windows + foreach (var ctx in additionalMonitorWindows) + { + if (ctx.BorderPath.Visibility != Visibility.Collapsed) + ctx.BorderPath.Visibility = Visibility.Collapsed; + if (ctx.HoverRing.Visibility != Visibility.Collapsed) + ctx.HoverRing.Visibility = Visibility.Collapsed; + if (ctx.BorderPath.Data != ctx.BaseGeometry) + ctx.BorderPath.Data = ctx.BaseGeometry; + } + + return; + } + + // --- Main Window Logic --- + if (frameOuterRect != null && frameInnerRect != null && hoverCursorRing != null && baseFrameGeometry != null) + { + var screen = GetCurrentScreen(); + if (screen != null) + { + ApplyHolePunchEffect( + screenX, screenY, + screen, + _dpiScaleX, _dpiScaleY, + frameOuterRect.Value, frameInnerRect.Value, + hoverCursorRing, + EdgeLightBorder, + baseFrameGeometry, + pathOffsetX, pathOffsetY, + (ring, x, y) => { Canvas.SetLeft(ring, x); Canvas.SetTop(ring, y); }, + primaryHoleCache + ); + } + } + + // --- Additional Windows Logic --- + foreach (var ctx in additionalMonitorWindows) + { + try + { + ApplyHolePunchEffect( + screenX, screenY, + ctx.Screen, + ctx.DpiScaleX, ctx.DpiScaleY, + ctx.FrameOuterRect, ctx.FrameInnerRect, + ctx.HoverRing, + ctx.BorderPath, + ctx.BaseGeometry, + ctx.PathOffsetX, ctx.PathOffsetY, + (ring, x, y) => { ring.Margin = new Thickness(x, y, 0, 0); }, + ctx.HoleCache + ); + } + catch (InvalidOperationException) + { + // Can happen if window is closing or not ready + } + } + } + + private void ApplyHolePunchEffect( + int screenX, int screenY, + Screen screen, + double dpiScaleX, double dpiScaleY, + Rect frameOuterRect, Rect frameInnerRect, + Ellipse hoverRing, + System.Windows.Shapes.Path borderPath, + Geometry baseGeometry, + double pathOffsetX, double pathOffsetY, + Action positionRing, + HoleCache holeCache) + { + // Manual coordinate calculation to avoid PointFromScreen issues across monitors/DPIs + // We positioned the window using dpiScaleX/Y relative to the screen WorkingArea. + double relX = (screenX - screen.WorkingArea.X) / dpiScaleX; + double relY = (screenY - screen.WorkingArea.Y) / dpiScaleY; + var windowPt = new System.Windows.Point(relX, relY); + + // Existing frame band detection (outer minus inner) + bool inFrameBand = frameOuterRect.Contains(windowPt) && !frameInnerRect.Contains(windowPt); + + // Early detection zone just inside the inner edge: a band with thickness = hole radius (cursor ring radius) + double ringDiameter = hoverRing.Width; + double holeRadius = ringDiameter / 2; // match ring size + var innerProximityRect = new Rect( + frameInnerRect.X + holeRadius, + frameInnerRect.Y + holeRadius, + frameInnerRect.Width - (holeRadius * 2), + frameInnerRect.Height - (holeRadius * 2)); + + // Near from inside means inside innerRect but within holeRadius of its edge (i.e., not deep inside innerProximityRect) + bool nearFromInside = frameInnerRect.Contains(windowPt) && !innerProximityRect.Contains(windowPt); + + bool overFrame = inFrameBand || nearFromInside; + + if (overFrame) + { + positionRing(hoverRing, windowPt.X - ringDiameter / 2, windowPt.Y - ringDiameter / 2); + + if (hoverRing.Visibility != Visibility.Visible) + { + hoverRing.Visibility = Visibility.Visible; + } + + // Punch a transparent hole under the ring by excluding a circle geometry from the frame + // Convert window coordinates to geometry local coordinates by subtracting stored offsets + var localCenter = new System.Windows.Point(windowPt.X - pathOffsetX, windowPt.Y - pathOffsetY); + if (holeCache.BaseGeometry != baseGeometry || + holeCache.Hole == null || + holeCache.Hole.RadiusX != holeRadius || + holeCache.Combined == null) + { + holeCache.BaseGeometry = baseGeometry; + holeCache.Hole = new EllipseGeometry(localCenter, holeRadius, holeRadius); + holeCache.Combined = new CombinedGeometry(GeometryCombineMode.Exclude, baseGeometry, holeCache.Hole); + } + else + { + holeCache.Hole.Center = localCenter; + } + + borderPath.Data = holeCache.Combined; + } + else + { + if (hoverRing.Visibility != Visibility.Collapsed) + { + hoverRing.Visibility = Visibility.Collapsed; + } + + if (borderPath.Visibility != Visibility.Visible) + { + borderPath.Visibility = Visibility.Visible; + } + // Restore original geometry (remove hole) + if (baseGeometry != null && borderPath.Data != baseGeometry) + { + borderPath.Data = baseGeometry; + } + } + } + + private void CreateControlWindow() + { + controlWindow = new ControlWindow(this); + RepositionControlWindow(); + + // Only show if controls are supposed to be visible + if (isControlWindowVisible) + { + controlWindow.Show(); + } + } + + private void CreateFrameGeometry() + { + // Get actual dimensions (accounting for margin) + double width = this.ActualWidth - 40; // 20px margin on each side + double height = this.ActualHeight - 40; + + const double frameThickness = 80; + const double outerRadius = 100; // Extra rounded like macOS + const double innerRadius = 60; // Keep proportional + + // Outer rounded rectangle + var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); + + // Inner rounded rectangle + var innerRect = new RectangleGeometry( + new Rect(frameThickness, frameThickness, + width - (frameThickness * 2), + height - (frameThickness * 2)), + innerRadius, innerRadius); + + // Combine: outer minus inner = frame + var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); + baseFrameGeometry = frameGeometry; // store original + EdgeLightBorder.Data = frameGeometry; + pathOffsetX = (ActualWidth - width) / 2.0; // store offsets for local coordinate conversion + pathOffsetY = (ActualHeight - height) / 2.0; + // Expand outer and contract inner rects for earlier hover detection based on ring hole radius. + double ringDiameter = hoverCursorRing?.Width ?? 0; + double holeRadius = ringDiameter / 2.0; + frameOuterRect = new Rect(pathOffsetX - holeRadius, pathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); + frameInnerRect = new Rect(pathOffsetX + frameThickness + holeRadius, pathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); + } + + private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + const int WM_HOTKEY = 0x0312; + + if (msg == WM_HOTKEY) + { + int hotkeyId = wParam.ToInt32(); + + switch (hotkeyId) + { + case HOTKEY_TOGGLE: + ToggleLight(); + handled = true; + break; + case HOTKEY_BRIGHTNESS_UP: + IncreaseBrightness(); + handled = true; + break; + case HOTKEY_BRIGHTNESS_DOWN: + DecreaseBrightness(); + handled = true; + break; + } + } + + return IntPtr.Zero; + } + + protected override void OnDpiChanged(DpiScale oldDpi, DpiScale newDpi) + { + base.OnDpiChanged(oldDpi, newDpi); + + _dpiScaleX = newDpi.DpiScaleX; + _dpiScaleY = newDpi.DpiScaleY; + + // Ensure window covers the current monitor correctly with new DPI + if (availableMonitors.Length > 0) + { + // Re-verify which monitor we are on, as we might have just moved + UpdateCurrentMonitorIndex(); + + if (currentMonitorIndex < availableMonitors.Length) + { + var screen = availableMonitors[currentMonitorIndex]; + var workingArea = screen.WorkingArea; + + // Only update if significantly different to avoid loops + double newLeft = workingArea.X / _dpiScaleX; + double newTop = workingArea.Y / _dpiScaleY; + double newWidth = workingArea.Width / _dpiScaleX; + double newHeight = workingArea.Height / _dpiScaleY; + + if (Math.Abs(this.Left - newLeft) > 1 || Math.Abs(this.Top - newTop) > 1 || + Math.Abs(this.Width - newWidth) > 1 || Math.Abs(this.Height - newHeight) > 1) + { + this.Left = newLeft; + this.Top = newTop; + this.Width = newWidth; + this.Height = newHeight; + } + } + } + } + + protected override void OnClosed(EventArgs e) + { + UninstallMouseHook(); + + var hwnd = new WindowInteropHelper(this).Handle; + UnregisterHotKey(hwnd, HOTKEY_TOGGLE); + UnregisterHotKey(hwnd, HOTKEY_BRIGHTNESS_UP); + UnregisterHotKey(hwnd, HOTKEY_BRIGHTNESS_DOWN); + + if (notifyIcon != null) + { + notifyIcon.Visible = false; + notifyIcon.Dispose(); + } + + HideAdditionalMonitorWindows(); + controlWindow?.Close(); + + base.OnClosed(e); + } + + private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) + { + if (e.Key == Key.L && + (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && + (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) + { + ToggleLight(); + } + else if (e.Key == Key.Escape) + { + System.Windows.Application.Current.Shutdown(); + } + } + + private void Toggle_Click(object sender, RoutedEventArgs e) + { + ToggleLight(); + } + + private void ToggleLight() + { + isLightOn = !isLightOn; + if (isLightOn) + { + EdgeLightBorder.Visibility = Visibility.Visible; + // Restore base geometry on toggle if needed + if (baseFrameGeometry != null) + { + EdgeLightBorder.Data = baseFrameGeometry; + } + } + else + { + EdgeLightBorder.Visibility = Visibility.Collapsed; + if (hoverCursorRing != null) + { + hoverCursorRing.Visibility = Visibility.Collapsed; + } + } + + // Update all additional monitor windows + UpdateAdditionalMonitorWindows(); + + settings.IsLightOn = isLightOn; + settings.Save(); + } + + public void HandleToggle() + { + ToggleLight(); + } + + public void ToggleControlsVisibility() + { + isControlWindowVisible = !isControlWindowVisible; + + // Apply visibility change if control window exists + if (controlWindow != null) + { + if (isControlWindowVisible) + { + controlWindow.Show(); + } + else + { + controlWindow.Hide(); + } + } + // Note: If controlWindow doesn't exist yet, isControlWindowVisible state + // is preserved and will be applied when CreateControlWindow() is called + + UpdateTrayMenuToggleControlsText(); + } + + private void UpdateTrayMenuToggleControlsText() + { + if (toggleControlsMenuItem != null) + { + toggleControlsMenuItem.Text = isControlWindowVisible ? "🎛️ Hide Controls" : "🎛️ Show Controls"; + } + } + + public void ToggleExcludeFromCapture() + { + settings.ExcludeFromCapture = !settings.ExcludeFromCapture; + settings.Save(); + + // Update menu checkmark + if (excludeFromCaptureMenuItem != null) + { + excludeFromCaptureMenuItem.Checked = settings.ExcludeFromCapture; + } + + // Apply the setting to all windows + ApplyExcludeFromCapture(); + } + + private void ApplyExcludeFromCapture() + { + var hwnd = new WindowInteropHelper(this).Handle; + if (hwnd != IntPtr.Zero) + { + var result = SetWindowDisplayAffinity(hwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); + if (!result) + { + var error = Marshal.GetLastWin32Error(); + System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for main window. Error: {error}"); + } + } + + // Apply to control window + if (controlWindow != null) + { + var controlHwnd = new WindowInteropHelper(controlWindow).Handle; + if (controlHwnd != IntPtr.Zero) + { + var result = SetWindowDisplayAffinity(controlHwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); + if (!result) + { + var error = Marshal.GetLastWin32Error(); + System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for control window. Error: {error}"); + } + } + } + + // Apply to all additional monitor windows + foreach (var ctx in additionalMonitorWindows) + { + var monitorHwnd = new WindowInteropHelper(ctx.Window).Handle; + if (monitorHwnd != IntPtr.Zero) + { + var result = SetWindowDisplayAffinity(monitorHwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); + if (!result) + { + var error = Marshal.GetLastWin32Error(); + System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for monitor window. Error: {error}"); + } + } + } + } + + public void IncreaseBrightness() + { + SetBrightness(currentOpacity + OpacityStep); + } + + public void DecreaseBrightness() + { + SetBrightness(currentOpacity - OpacityStep); + } + + public void SetBrightness(double value, bool save = true) + { + currentOpacity = Math.Max(MinOpacity, Math.Min(MaxOpacity, value)); + EdgeLightBorder.Opacity = currentOpacity; + UpdateAdditionalMonitorWindows(); + + if (save) + { + settings.Brightness = currentOpacity; + settings.Save(); + } + } + + private void UpdateAdditionalMonitorWindows() + { + foreach (var ctx in additionalMonitorWindows) + { + var path = ctx.BorderPath; + path.Opacity = currentOpacity; + path.Visibility = isLightOn ? Visibility.Visible : Visibility.Collapsed; + ApplyColorTemperature(path); + } + } + + public void IncreaseColorTemperature() + { + SetColorTemperature(_colorTemperature + ColorTempStep); + } + + public void DecreaseColorTemperature() + { + SetColorTemperature(_colorTemperature - ColorTempStep); + } + + public void SetColorTemperature(double value, bool save = true) + { + _colorTemperature = Math.Max(MinColorTemp, Math.Min(MaxColorTemp, value)); + ApplyColorTemperature(EdgeLightBorder); + + // Update all additional monitor windows + UpdateAdditionalMonitorWindows(); + + if (save) + { + settings.ColorTemperature = _colorTemperature; + settings.Save(); + } + } + + public void MoveToNextMonitor() + { + // If in all monitors mode, do nothing + if (showOnAllMonitors) return; + + // Refresh monitor list in case of hot-plug/unplug + RefreshAvailableMonitors(); + + if (availableMonitors.Length <= 1) + { + return; + } + + // Ensure currentMonitorIndex is accurate before moving + UpdateCurrentMonitorIndex(); + + _isManualMonitorSwitch = true; + try + { + // Cycle to next monitor + currentMonitorIndex = (currentMonitorIndex + 1) % availableMonitors.Length; + var targetScreen = availableMonitors[currentMonitorIndex]; + + // Reposition main window to new monitor using physical coordinates to trigger DPI change correctly + var hwnd = new WindowInteropHelper(this).Handle; + SetWindowPos(hwnd, IntPtr.Zero, + targetScreen.WorkingArea.X, targetScreen.WorkingArea.Y, + targetScreen.WorkingArea.Width, targetScreen.WorkingArea.Height, + SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); + + // Force a size update if DPI didn't change (SetWindowPos might not trigger OnDpiChanged) + // If DPI changed, OnDpiChanged will handle it. + // But we can't easily know if OnDpiChanged fired yet. + // However, setting properties to the same value is cheap in WPF. + // We need to ensure we use the NEW DPI if it changed. + // OnDpiChanged updates _dpiScaleX/Y. + + // If we are on the same thread, OnDpiChanged (via WM_DPICHANGED) should have fired synchronously during SetWindowPos. + // So _dpiScaleX/Y should be up to date. + + double newLeft = targetScreen.WorkingArea.X / _dpiScaleX; + double newTop = targetScreen.WorkingArea.Y / _dpiScaleY; + double newWidth = targetScreen.WorkingArea.Width / _dpiScaleX; + double newHeight = targetScreen.WorkingArea.Height / _dpiScaleY; + + this.Left = newLeft; + this.Top = newTop; + this.Width = newWidth; + this.Height = newHeight; + } + finally + { + _isManualMonitorSwitch = false; + } + + // An explicit monitor switch should bring the controls to the selected monitor. + ResetControlWindowPosition(); + } + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); + private const uint SWP_NOZORDER = 0x0004; + private const uint SWP_NOACTIVATE = 0x0010; + private const uint SWP_FRAMECHANGED = 0x0020; + + public void ToggleAllMonitors() + { + showOnAllMonitors = !showOnAllMonitors; + + if (showOnAllMonitors) + { + ShowOnAllMonitors(); + } + else + { + HideAdditionalMonitorWindows(); + } + + controlWindow?.UpdateAllMonitorsButtonState(); + } + + private void ShowOnAllMonitors() + { + RefreshAvailableMonitors(); + + // Close any existing additional windows + HideAdditionalMonitorWindows(); + + // Create a window for each monitor except the current one (this window) + for (int i = 0; i < availableMonitors.Length; i++) + { + if (i != currentMonitorIndex) + { + var monitorCtx = CreateMonitorWindow(availableMonitors[i]); + additionalMonitorWindows.Add(monitorCtx); + monitorCtx.Window.Show(); + } + } + } + + private void HideAdditionalMonitorWindows() + { + foreach (var ctx in additionalMonitorWindows) + { + ctx.Window.Close(); + } + additionalMonitorWindows.Clear(); + } + + private MonitorWindowContext CreateMonitorWindow(Screen screen) + { + var window = new Window + { + Title = "Windows Edge Light", + AllowsTransparency = true, + Background = System.Windows.Media.Brushes.Transparent, + ResizeMode = ResizeMode.NoResize, + ShowInTaskbar = false, + Topmost = true, + WindowStyle = WindowStyle.None + }; + + // Position on the target screen + var workingArea = screen.WorkingArea; + + // Get the correct DPI scale for THIS specific screen + var (screenDpiX, screenDpiY) = GetDpiForScreen(screen); + + // Convert physical pixels to WPF DIPs using the correct per-monitor DPI + window.Left = workingArea.X / screenDpiX; + window.Top = workingArea.Y / screenDpiY; + window.Width = workingArea.Width / screenDpiX; + window.Height = workingArea.Height / screenDpiY; + + // Create the grid and edge light border + var grid = new System.Windows.Controls.Grid { IsHitTestVisible = false }; + var path = new System.Windows.Shapes.Path + { + HorizontalAlignment = System.Windows.HorizontalAlignment.Center, + VerticalAlignment = System.Windows.VerticalAlignment.Center, + Stretch = System.Windows.Media.Stretch.None, + Opacity = currentOpacity, + Visibility = isLightOn ? Visibility.Visible : Visibility.Collapsed + }; + + var temperatureColor = GetColorForTemperature(_colorTemperature); + var gradient = new LinearGradientBrush + { + StartPoint = new System.Windows.Point(0, 0), + EndPoint = new System.Windows.Point(1, 1) + }; + gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 0.0)); + gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.3)); + gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.5)); + gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.7)); + gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 1.0)); + path.Fill = gradient; + + // Add drop shadow effect + path.Effect = new DropShadowEffect + { + BlurRadius = 76, + Opacity = 1, + ShadowDepth = 0, + Color = temperatureColor + }; + + // Create hover ring (Ellipse) + var hoverRing = new Ellipse + { + Width = 140, + Height = 140, + Fill = System.Windows.Media.Brushes.Transparent, + Visibility = Visibility.Collapsed, + HorizontalAlignment = System.Windows.HorizontalAlignment.Left, + VerticalAlignment = System.Windows.VerticalAlignment.Top + }; + // Add drop shadow to ring - actually main window doesn't seem to have this on the ring itself? + // Main window XAML doesn't show effect on HoverCursorRing. + // So removing effect to match. + + // Create frame geometry + double width = window.Width - 40; + double height = window.Height - 40; + const double frameThickness = 80; + const double outerRadius = 100; + const double innerRadius = 60; + + var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); + var innerRect = new RectangleGeometry( + new Rect(frameThickness, frameThickness, + width - (frameThickness * 2), + height - (frameThickness * 2)), + innerRadius, innerRadius); + + var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); + path.Data = frameGeometry; + + grid.Children.Add(path); + grid.Children.Add(hoverRing); + window.Content = grid; + + // Calculate geometry data for hole punch + double pathOffsetX = (window.Width - width) / 2.0; + double pathOffsetY = (window.Height - height) / 2.0; + + double ringDiameter = hoverRing.Width; + double holeRadius = ringDiameter / 2.0; + var frameOuterRect = new Rect(pathOffsetX - holeRadius, pathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); + var frameInnerRect = new Rect(pathOffsetX + frameThickness + holeRadius, pathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); + + var ctx = new MonitorWindowContext + { + Window = window, + Screen = screen, + BorderPath = path, + HoverRing = hoverRing, + BaseGeometry = frameGeometry, + FrameOuterRect = frameOuterRect, + FrameInnerRect = frameInnerRect, + PathOffsetX = pathOffsetX, + PathOffsetY = pathOffsetY, + DpiScaleX = screenDpiX, // Use calculated DPI for this screen + DpiScaleY = screenDpiY + }; + + // Make window click-through and handle DPI + window.Loaded += (s, e) => + { + var hwnd = new WindowInteropHelper(window).Handle; + int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); + SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT | WS_EX_LAYERED); + + // Apply exclude from capture setting + var result = SetWindowDisplayAffinity(hwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); + if (!result) + { + var error = Marshal.GetLastWin32Error(); + System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for monitor window during creation. Error: {error}"); + } + + // Verify and update DPI if WPF reports a different value after window is loaded + var source = PresentationSource.FromVisual(window); + if (source != null) + { + double dpiX = source.CompositionTarget.TransformToDevice.M11; + double dpiY = source.CompositionTarget.TransformToDevice.M22; + + // Only reposition if DPI changed significantly from our initial calculation + if (Math.Abs(dpiX - ctx.DpiScaleX) > 0.01 || Math.Abs(dpiY - ctx.DpiScaleY) > 0.01) + { + ctx.DpiScaleX = dpiX; + ctx.DpiScaleY = dpiY; + + // Reposition/Resize with correct DPI + window.Left = screen.WorkingArea.X / dpiX; + window.Top = screen.WorkingArea.Y / dpiY; + window.Width = screen.WorkingArea.Width / dpiX; + window.Height = screen.WorkingArea.Height / dpiY; + + // Recalculate geometry for new window size + UpdateMonitorGeometry(ctx); + } + } + }; + + window.DpiChanged += (s, dpiArgs) => + { + ctx.DpiScaleX = dpiArgs.NewDpi.DpiScaleX; + ctx.DpiScaleY = dpiArgs.NewDpi.DpiScaleY; + + window.Left = screen.WorkingArea.X / ctx.DpiScaleX; + window.Top = screen.WorkingArea.Y / ctx.DpiScaleY; + window.Width = screen.WorkingArea.Width / ctx.DpiScaleX; + window.Height = screen.WorkingArea.Height / ctx.DpiScaleY; + + UpdateMonitorGeometry(ctx); + }; + + return ctx; + } + + private void UpdateMonitorGeometry(MonitorWindowContext ctx) + { + double width = ctx.Window.Width - 40; + double height = ctx.Window.Height - 40; + const double frameThickness = 80; + const double outerRadius = 100; + const double innerRadius = 60; + + var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); + var innerRect = new RectangleGeometry( + new Rect(frameThickness, frameThickness, + width - (frameThickness * 2), + height - (frameThickness * 2)), + innerRadius, innerRadius); + + var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); + + ctx.BaseGeometry = frameGeometry; + ctx.BorderPath.Data = frameGeometry; + + ctx.PathOffsetX = (ctx.Window.Width - width) / 2.0; + ctx.PathOffsetY = (ctx.Window.Height - height) / 2.0; + + double ringDiameter = ctx.HoverRing.Width; + double holeRadius = ringDiameter / 2.0; + + ctx.FrameOuterRect = new Rect(ctx.PathOffsetX - holeRadius, ctx.PathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); + ctx.FrameInnerRect = new Rect(ctx.PathOffsetX + frameThickness + holeRadius, ctx.PathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); + } + + public bool IsShowingOnAllMonitors() + { + return showOnAllMonitors; + } + + private void RepositionControlWindow() + { + if (controlWindow == null) return; + + // Respect a user-dragged position for the current session. + if (controlWindowManuallyMoved) return; + + // Position at bottom center of main window + controlWindow.Left = this.Left + (this.Width - controlWindow.Width) / 2; + controlWindow.Top = this.Top + this.Height - controlWindow.Height - 124; + } + + public void NotifyControlWindowManuallyMoved() + { + controlWindowManuallyMoved = true; + } + + public void ResetControlWindowPosition() + { + controlWindowManuallyMoved = false; + RepositionControlWindow(); + } + + public bool HasMultipleMonitors() + { + // Refresh monitor count to handle hot-plug scenarios + RefreshAvailableMonitors(); + return availableMonitors.Length > 1; + } + + public bool IsExcludeFromCaptureEnabled() + { + return settings.ExcludeFromCapture; + } + + public double GetBrightness() => currentOpacity; + + public double GetColorTemperature() => _colorTemperature; + + public void SaveAppearanceSettings() + { + settings.Brightness = currentOpacity; + settings.ColorTemperature = _colorTemperature; + settings.Save(); + } + + public bool GetIsToggleButtonVisible() => settings.ShowToggleButton; + + public bool GetIsBrightnessButtonsVisible() => settings.ShowBrightnessButtons; + + public bool GetIsColorTempButtonsVisible() => settings.ShowColorTempButtons; + + public bool GetIsControlMonitorsButtonVisible() => settings.ShowMonitorControlButtons; + + public void SetIsToggleVisible(bool isVisible) + { + settings.ShowToggleButton = isVisible; + settings.Save(); + } + + public void SetIsBrightnessButtonsVisible(bool isVisible) + { + settings.ShowBrightnessButtons = isVisible; + settings.Save(); + } + + public void SetIsColorTempButtonsVisible(bool isVisible) + { + settings.ShowColorTempButtons = isVisible; + settings.Save(); + } + + public void SetIsControlMonitorsButtonVisible(bool isVisible) + { + settings.ShowMonitorControlButtons = isVisible; + settings.Save(); + } + + private void Window_SizeChanged(object sender, SizeChangedEventArgs e) + { + // Recreate geometry when window size changes (e.g., different monitor resolution) + if (EdgeLightBorder != null) + { + CreateFrameGeometry(); + } + + // Reposition control window + RepositionControlWindow(); + + // Update which monitor we're actually on + UpdateCurrentMonitorIndex(); + } + + private void Window_LocationChanged(object? sender, EventArgs e) + { + // Reposition control window when main window moves + RepositionControlWindow(); + + // Update which monitor we're actually on + UpdateCurrentMonitorIndex(); + } + + private void UpdateCurrentMonitorIndex() + { + // If we are manually switching, trust the index we set explicitly + if (_isManualMonitorSwitch) return; + + RefreshAvailableMonitors(); + + if (availableMonitors.Length == 0) return; + + try + { + // Use PointToScreen to get accurate physical coordinates of the window center + // This handles DPI scaling correctly unlike manual calculation + var centerPoint = this.PointToScreen(new System.Windows.Point(this.ActualWidth / 2, this.ActualHeight / 2)); + var drawingPoint = new System.Drawing.Point((int)centerPoint.X, (int)centerPoint.Y); + + for (int i = 0; i < availableMonitors.Length; i++) + { + if (availableMonitors[i].Bounds.Contains(drawingPoint)) + { + currentMonitorIndex = i; + break; + } + } + } + catch (InvalidOperationException) + { + // Window might not be loaded or visible yet + } + } + + private void RefreshAvailableMonitors() + { + availableMonitors = Screen.AllScreens; + currentMonitorIndex = availableMonitors.Length == 0 + ? 0 + : Math.Clamp(currentMonitorIndex, 0, availableMonitors.Length - 1); + } + + private Screen? GetCurrentScreen() + { + if (availableMonitors.Length == 0) + { + return Screen.PrimaryScreen; + } + + currentMonitorIndex = Math.Clamp(currentMonitorIndex, 0, availableMonitors.Length - 1); + return availableMonitors[currentMonitorIndex]; + } + + private static MediaColor GetColorForTemperature(double temperature) + { + byte Lerp(byte cool, byte warm) => (byte)(cool + ((warm - cool) * temperature)); + return MediaColor.FromRgb( + Lerp(CoolColor.R, WarmColor.R), + Lerp(CoolColor.G, WarmColor.G), + Lerp(CoolColor.B, WarmColor.B)); + } + + private void ApplyColorTemperature(System.Windows.Shapes.Path path) + { + var temperatureColor = GetColorForTemperature(_colorTemperature); + + if (path.Fill is LinearGradientBrush brush) + { + foreach (var stop in brush.GradientStops) + { + if (stop.Offset is > 0.2 and < 0.8) + { + stop.Color = temperatureColor; + } + } + } + + if (path.Effect is DropShadowEffect shadow) + { + shadow.Color = temperatureColor; + } + } + + private (double dpiScaleX, double dpiScaleY) GetDpiForScreen(Screen screen) + { + try + { + // Get monitor handle for the center of the screen + var centerPoint = new POINT + { + x = screen.Bounds.X + screen.Bounds.Width / 2, + y = screen.Bounds.Y + screen.Bounds.Height / 2 + }; + + IntPtr hMonitor = MonitorFromPoint(centerPoint, MONITOR_DEFAULTTONEAREST); + + if (hMonitor != IntPtr.Zero) + { + int result = GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, out uint dpiX, out uint dpiY); + if (result == 0) // S_OK + { + // Convert from DPI to scale factor (96 DPI = 100% = 1.0) + return (dpiX / 96.0, dpiY / 96.0); + } + } + } + catch + { + // Fall through to default + } + + // Fallback: return 1.0 (100% scaling) + return (1.0, 1.0); + } + + private void BrightnessUp_Click(object sender, RoutedEventArgs e) + { + IncreaseBrightness(); + } + + private void BrightnessDown_Click(object sender, RoutedEventArgs e) + { + DecreaseBrightness(); + } + + private void Close_Click(object sender, RoutedEventArgs e) + { + System.Windows.Application.Current.Shutdown(); + } + + private const int GWL_EXSTYLE = -20; + private const int WS_EX_TRANSPARENT = 0x00000020; + private const int WS_EX_LAYERED = 0x00080000; + + [DllImport("user32.dll")] + private static extern int GetWindowLong(IntPtr hwnd, int index); + + [DllImport("user32.dll")] + private static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle); } \ No newline at end of file diff --git a/WindowsEdgeLight/SettingsWindow.xaml.cs b/WindowsEdgeLight/SettingsWindow.xaml.cs index 0128cf6..74648b8 100644 --- a/WindowsEdgeLight/SettingsWindow.xaml.cs +++ b/WindowsEdgeLight/SettingsWindow.xaml.cs @@ -1,148 +1,158 @@ -using System.Windows; -using System.Windows.Controls; - -namespace WindowsEdgeLight; - -public partial class SettingsWindow : Window -{ - private readonly MainWindow mainWindow; - private bool isInitializing = true; - - public SettingsWindow(MainWindow main) - { - InitializeComponent(); - mainWindow = main; - - BrightnessSlider.Value = mainWindow.GetBrightness(); - ColorTempSlider.Value = mainWindow.GetColorTemperature(); - ExcludeFromCaptureCheckBox.IsChecked = mainWindow.IsExcludeFromCaptureEnabled(); - ShowBrightnessCheckBox.IsChecked = mainWindow.GetIsBrightnessButtonsVisible(); - ShowColorTempCheckBox.IsChecked = mainWindow.GetIsColorTempButtonsVisible(); - ShowMonitorControlsCheckBox.IsChecked = mainWindow.GetIsControlMonitorsButtonVisible(); - ShowToggleCheckBox.IsChecked = mainWindow.GetIsToggleButtonVisible(); - - UpdateBrightnessLabel(); - UpdateColorTempLabel(); - - isInitializing = false; - } - - private void BrightnessSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) - { - if (isInitializing) return; - mainWindow.SetBrightness(e.NewValue, save: false); - UpdateBrightnessLabel(); - } - - private void BrightnessSlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) - { - mainWindow.SetBrightness(BrightnessSlider.Value, save: true); - } - - private void ColorTempSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) - { - if (isInitializing) return; - mainWindow.SetColorTemperature(e.NewValue, save: false); - UpdateColorTempLabel(); - } - - private void ColorTempSlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) - { - mainWindow.SetColorTemperature(ColorTempSlider.Value, save: true); - } - - private void SettingsWindow_Loaded(object sender, RoutedEventArgs e) - { - if (Owner == null) - { - return; - } - - const double gap = 12; - var workArea = SystemParameters.WorkArea; - MaxHeight = Math.Max(200, workArea.Height - (gap * 2)); - var desiredLeft = Owner.Left + ((Owner.ActualWidth - ActualWidth) / 2); - Left = Math.Min(Math.Max(desiredLeft, workArea.Left + gap), workArea.Right - ActualWidth - gap); - - var aboveOwnerTop = Owner.Top - ActualHeight - gap; - if (aboveOwnerTop >= workArea.Top + gap) - { - Top = aboveOwnerTop; - return; - } - - var belowOwnerTop = Owner.Top + Owner.ActualHeight + gap; - if (belowOwnerTop + ActualHeight <= workArea.Bottom - gap) - { - Top = belowOwnerTop; - return; - } - - Top = workArea.Top + ((workArea.Height - ActualHeight) / 2); - } - - private void SettingsWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e) - { - mainWindow.SetBrightness(BrightnessSlider.Value, save: true); - mainWindow.SetColorTemperature(ColorTempSlider.Value, save: true); - } - - private void ExcludeFromCapture_Click(object sender, RoutedEventArgs e) - { - bool current = mainWindow.IsExcludeFromCaptureEnabled(); - bool desired = ExcludeFromCaptureCheckBox.IsChecked == true; - if (current != desired) - { - mainWindow.ToggleExcludeFromCapture(); - } - } - - private void UpdateBrightnessLabel() - { - if (BrightnessValueText != null) - BrightnessValueText.Text = $"{(int)(BrightnessSlider.Value * 100)}%"; - } - - private void UpdateColorTempLabel() - { - if (ColorTempValueText != null) - ColorTempValueText.Text = $"{(int)(ColorTempSlider.Value * 100)}%"; - } - - private void ShowToggle_Click(object sender, RoutedEventArgs e) - { - mainWindow.SetIsToggleVisible(ShowToggleCheckBox.IsChecked == true); - UpdateOwnerControlWindow(); - } - - private void ShowBrightness_Click(object sender, RoutedEventArgs e) - { - mainWindow.SetIsBrightnessButtonsVisible(ShowBrightnessCheckBox.IsChecked == true); - UpdateOwnerControlWindow(); - } - - private void ShowColorTemp_Click(object sender, RoutedEventArgs e) - { - mainWindow.SetIsColorTempButtonsVisible(ShowColorTempCheckBox.IsChecked == true); - UpdateOwnerControlWindow(); - } - - private void ShowMonitorControls_Click(object sender, RoutedEventArgs e) - { - mainWindow.SetIsControlMonitorsButtonVisible(ShowMonitorControlsCheckBox.IsChecked == true); - UpdateOwnerControlWindow(); - } - - private void ResetControlBarPosition_Click(object sender, RoutedEventArgs e) - { - mainWindow.ResetControlWindowPosition(); - } - - private void UpdateOwnerControlWindow() - { - if (Owner is ControlWindow controlWindow) - { - controlWindow.ApplyButtonVisibility(); - } - } -} +using System.Windows; +using System.Windows.Controls; +using System.Windows.Interop; +using System.Windows.Media; + +namespace WindowsEdgeLight; + +public partial class SettingsWindow : Window +{ + private readonly MainWindow mainWindow; + private bool isInitializing = true; + + public SettingsWindow(MainWindow main) + { + InitializeComponent(); + mainWindow = main; + + BrightnessSlider.Value = mainWindow.GetBrightness(); + ColorTempSlider.Value = mainWindow.GetColorTemperature(); + ExcludeFromCaptureCheckBox.IsChecked = mainWindow.IsExcludeFromCaptureEnabled(); + ShowBrightnessCheckBox.IsChecked = mainWindow.GetIsBrightnessButtonsVisible(); + ShowColorTempCheckBox.IsChecked = mainWindow.GetIsColorTempButtonsVisible(); + ShowMonitorControlsCheckBox.IsChecked = mainWindow.GetIsControlMonitorsButtonVisible(); + ShowToggleCheckBox.IsChecked = mainWindow.GetIsToggleButtonVisible(); + + UpdateBrightnessLabel(); + UpdateColorTempLabel(); + + isInitializing = false; + } + + private void BrightnessSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) + { + if (isInitializing) return; + mainWindow.SetBrightness(e.NewValue, save: false); + UpdateBrightnessLabel(); + } + + private void BrightnessSlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) + { + mainWindow.SetBrightness(BrightnessSlider.Value, save: true); + } + + private void ColorTempSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) + { + if (isInitializing) return; + mainWindow.SetColorTemperature(e.NewValue, save: false); + UpdateColorTempLabel(); + } + + private void ColorTempSlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) + { + mainWindow.SetColorTemperature(ColorTempSlider.Value, save: true); + } + + private void SettingsWindow_Loaded(object sender, RoutedEventArgs e) + { + if (Owner == null) + { + return; + } + + const double gap = 12; + var ownerHandle = new WindowInteropHelper(Owner).Handle; + var screen = System.Windows.Forms.Screen.FromHandle(ownerHandle); + var transformFromDevice = PresentationSource.FromVisual(Owner)? + .CompositionTarget?.TransformFromDevice ?? Matrix.Identity; + var workArea = new Rect( + screen.WorkingArea.X * transformFromDevice.M11, + screen.WorkingArea.Y * transformFromDevice.M22, + screen.WorkingArea.Width * transformFromDevice.M11, + screen.WorkingArea.Height * transformFromDevice.M22); + + MaxHeight = Math.Max(200, workArea.Height - (gap * 2)); + var desiredLeft = Owner.Left + ((Owner.ActualWidth - ActualWidth) / 2); + Left = Math.Min(Math.Max(desiredLeft, workArea.Left + gap), workArea.Right - ActualWidth - gap); + + var aboveOwnerTop = Owner.Top - ActualHeight - gap; + if (aboveOwnerTop >= workArea.Top + gap) + { + Top = aboveOwnerTop; + return; + } + + var belowOwnerTop = Owner.Top + Owner.ActualHeight + gap; + if (belowOwnerTop + ActualHeight <= workArea.Bottom - gap) + { + Top = belowOwnerTop; + return; + } + + Top = workArea.Top + ((workArea.Height - ActualHeight) / 2); + } + + private void SettingsWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e) + { + mainWindow.SaveAppearanceSettings(); + } + + private void ExcludeFromCapture_Click(object sender, RoutedEventArgs e) + { + bool current = mainWindow.IsExcludeFromCaptureEnabled(); + bool desired = ExcludeFromCaptureCheckBox.IsChecked == true; + if (current != desired) + { + mainWindow.ToggleExcludeFromCapture(); + } + } + + private void UpdateBrightnessLabel() + { + if (BrightnessValueText != null) + BrightnessValueText.Text = $"{(int)(BrightnessSlider.Value * 100)}%"; + } + + private void UpdateColorTempLabel() + { + if (ColorTempValueText != null) + ColorTempValueText.Text = $"{(int)(ColorTempSlider.Value * 100)}%"; + } + + private void ShowToggle_Click(object sender, RoutedEventArgs e) + { + mainWindow.SetIsToggleVisible(ShowToggleCheckBox.IsChecked == true); + UpdateOwnerControlWindow(); + } + + private void ShowBrightness_Click(object sender, RoutedEventArgs e) + { + mainWindow.SetIsBrightnessButtonsVisible(ShowBrightnessCheckBox.IsChecked == true); + UpdateOwnerControlWindow(); + } + + private void ShowColorTemp_Click(object sender, RoutedEventArgs e) + { + mainWindow.SetIsColorTempButtonsVisible(ShowColorTempCheckBox.IsChecked == true); + UpdateOwnerControlWindow(); + } + + private void ShowMonitorControls_Click(object sender, RoutedEventArgs e) + { + mainWindow.SetIsControlMonitorsButtonVisible(ShowMonitorControlsCheckBox.IsChecked == true); + UpdateOwnerControlWindow(); + } + + private void ResetControlBarPosition_Click(object sender, RoutedEventArgs e) + { + mainWindow.ResetControlWindowPosition(); + } + + private void UpdateOwnerControlWindow() + { + if (Owner is ControlWindow controlWindow) + { + controlWindow.ApplyButtonVisibility(); + } + } +} From 6a336ad5e43af325093339b507af503ce713dc0a Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Fri, 7 Aug 2026 22:28:56 -0700 Subject: [PATCH 2/2] Normalize PR file line endings Replace the raw CRLF working-tree upload with Git-normalized blobs so the PR contains only intentional changes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 83256e33-0073-41df-8635-10e4fba2ec65 --- .github/workflows/build.yml | 330 +- .github/workflows/ci.yml | 88 +- README.md | 410 +-- WindowsEdgeLight.Tests/AppSettingsTests.cs | 274 +- .../WindowsEdgeLight.Tests.csproj | 48 +- WindowsEdgeLight.sln | 60 +- WindowsEdgeLight/AppSettings.cs | 274 +- WindowsEdgeLight/AssemblyInfo.cs | 26 +- WindowsEdgeLight/ControlWindow.xaml.cs | 238 +- WindowsEdgeLight/MainWindow.xaml.cs | 2944 ++++++++--------- WindowsEdgeLight/SettingsWindow.xaml.cs | 316 +- 11 files changed, 2504 insertions(+), 2504 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 360ea58..f963543 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,165 +1,165 @@ -name: Build Release - -on: - push: - tags: - - 'v*' - workflow_dispatch: - -permissions: - contents: write - -jobs: - build: - runs-on: windows-latest - - steps: - - name: Checkout code - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: '10.0.x' - - - name: Cache NuGet packages - uses: actions/cache@v4 - with: - path: ~\.nuget\packages - key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }} - restore-keys: | - ${{ runner.os }}-nuget- - - - name: Restore dependencies - run: dotnet restore WindowsEdgeLight/WindowsEdgeLight.csproj - - - name: Install GitVersion - uses: gittools/actions/gitversion/setup@v4 - with: - versionSpec: '6.4.x' - - - name: GitVersion - uses: gittools/actions/gitversion/execute@v4 - id: gitversion - - - name: Set version environment variables - shell: pwsh - run: | - # Use GitVersion outputs for all versioning - $version = '${{ steps.gitversion.outputs.semVer }}' - $fullVersion = '${{ steps.gitversion.outputs.fullSemVer }}' - - # Assembly version must be 4-part (x.y.z.w) - $assemblyVersion = "${{ steps.gitversion.outputs.major }}.${{ steps.gitversion.outputs.minor }}.${{ steps.gitversion.outputs.patch }}.0" - - Write-Host "Using semantic version: $version" - Write-Host "Using full version: $fullVersion" - Write-Host "Using assembly version: $assemblyVersion" - - echo "VERSION=$version" >> $env:GITHUB_ENV - echo "FULLVERSION=$fullVersion" >> $env:GITHUB_ENV - echo "ASSEMBLY_VERSION=$assemblyVersion" >> $env:GITHUB_ENV - - - name: Build x64 - run: | - dotnet publish WindowsEdgeLight/WindowsEdgeLight.csproj ` - -c Release ` - -r win-x64 ` - /p:DebugType=None ` - /p:DebugSymbols=false ` - /p:Version=$env:VERSION ` - /p:AssemblyVersion=$env:ASSEMBLY_VERSION ` - /p:FileVersion=$env:ASSEMBLY_VERSION ` - /p:AssemblyInformationalVersion=$env:FULLVERSION ` - --self-contained - - - name: Build ARM64 - run: | - dotnet publish WindowsEdgeLight/WindowsEdgeLight.csproj ` - -c Release ` - -r win-arm64 ` - /p:DebugType=None ` - /p:DebugSymbols=false ` - /p:Version=$env:VERSION ` - /p:AssemblyVersion=$env:ASSEMBLY_VERSION ` - /p:FileVersion=$env:ASSEMBLY_VERSION ` - /p:AssemblyInformationalVersion=$env:FULLVERSION ` - --self-contained - - - name: Azure Login - uses: azure/login@v2 - with: - creds: '{"clientId":"${{ secrets.AZURE_CLIENT_ID }}","clientSecret":"${{ secrets.AZURE_CLIENT_SECRET }}","subscriptionId":"${{ secrets.AZURE_SUBSCRIPTION_ID }}","tenantId":"${{ secrets.AZURE_TENANT_ID }}"}' - - - name: Sign executables with Trusted Signing - uses: azure/trusted-signing-action@v1 - with: - azure-tenant-id: ${{ secrets.AZURE_TENANT_ID }} - azure-client-id: ${{ secrets.AZURE_CLIENT_ID }} - azure-client-secret: ${{ secrets.AZURE_CLIENT_SECRET }} - endpoint: https://wus2.codesigning.azure.net/ - signing-account-name: hanselman - certificate-profile-name: WindowsEdgeLight - files-folder: ${{ github.workspace }}\WindowsEdgeLight\bin\Release\net10.0-windows - files-folder-filter: exe - files-folder-recurse: true - file-digest: SHA256 - timestamp-rfc3161: http://timestamp.acs.microsoft.com - timestamp-digest: SHA256 - - - name: Prepare artifacts - shell: pwsh - run: | - New-Item -ItemType Directory -Path artifacts -Force - # Use VERSION environment variable (calculated via GitVersion) - $version = $env:VERSION - - # Create ZIP files with exe and README (so Updatum treats as portable app) - New-Item -ItemType Directory -Path "temp-x64" -Force - Copy-Item "WindowsEdgeLight/bin/Release/net10.0-windows/win-x64/publish/WindowsEdgeLight.exe" -Destination "temp-x64/" - Copy-Item "README.md" -Destination "temp-x64/" - Compress-Archive -Path "temp-x64/*" -DestinationPath "artifacts/WindowsEdgeLight-v$version-win-x64.zip" - - New-Item -ItemType Directory -Path "temp-arm64" -Force - Copy-Item "WindowsEdgeLight/bin/Release/net10.0-windows/win-arm64/publish/WindowsEdgeLight.exe" -Destination "temp-arm64/" - Copy-Item "README.md" -Destination "temp-arm64/" - Compress-Archive -Path "temp-arm64/*" -DestinationPath "artifacts/WindowsEdgeLight-v$version-win-arm64.zip" - - Remove-Item "temp-x64" -Recurse -Force - Remove-Item "temp-arm64" -Recurse -Force - - - name: Upload artifacts - uses: actions/upload-artifact@v4 - with: - name: WindowsEdgeLight-Release - path: artifacts/*.zip - - - name: Create Release - if: startsWith(github.ref, 'refs/tags/') - uses: softprops/action-gh-release@v2 - with: - files: artifacts/*.zip - generate_release_notes: true - body: | - ## Windows Edge Light ${{ github.ref_name }} - - ### 📦 Downloads - - | File | Platform | - |------|----------| - | `WindowsEdgeLight-${{ github.ref_name }}-win-x64.zip` | Intel/AMD 64-bit Windows | - | `WindowsEdgeLight-${{ github.ref_name }}-win-arm64.zip` | ARM64 Windows (Surface Pro X, etc.) | - - **Self-contained** - Extract and run, no .NET installation required. - - ### ⌨️ Keyboard Shortcuts - - `Ctrl+Shift+L` - Toggle light on/off - - `Ctrl+Shift+↑` - Increase brightness - - `Ctrl+Shift+↓` - Decrease brightness - - --- - append_body: true - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +name: Build Release + +on: + push: + tags: + - 'v*' + workflow_dispatch: + +permissions: + contents: write + +jobs: + build: + runs-on: windows-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Cache NuGet packages + uses: actions/cache@v4 + with: + path: ~\.nuget\packages + key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }} + restore-keys: | + ${{ runner.os }}-nuget- + + - name: Restore dependencies + run: dotnet restore WindowsEdgeLight/WindowsEdgeLight.csproj + + - name: Install GitVersion + uses: gittools/actions/gitversion/setup@v4 + with: + versionSpec: '6.4.x' + + - name: GitVersion + uses: gittools/actions/gitversion/execute@v4 + id: gitversion + + - name: Set version environment variables + shell: pwsh + run: | + # Use GitVersion outputs for all versioning + $version = '${{ steps.gitversion.outputs.semVer }}' + $fullVersion = '${{ steps.gitversion.outputs.fullSemVer }}' + + # Assembly version must be 4-part (x.y.z.w) + $assemblyVersion = "${{ steps.gitversion.outputs.major }}.${{ steps.gitversion.outputs.minor }}.${{ steps.gitversion.outputs.patch }}.0" + + Write-Host "Using semantic version: $version" + Write-Host "Using full version: $fullVersion" + Write-Host "Using assembly version: $assemblyVersion" + + echo "VERSION=$version" >> $env:GITHUB_ENV + echo "FULLVERSION=$fullVersion" >> $env:GITHUB_ENV + echo "ASSEMBLY_VERSION=$assemblyVersion" >> $env:GITHUB_ENV + + - name: Build x64 + run: | + dotnet publish WindowsEdgeLight/WindowsEdgeLight.csproj ` + -c Release ` + -r win-x64 ` + /p:DebugType=None ` + /p:DebugSymbols=false ` + /p:Version=$env:VERSION ` + /p:AssemblyVersion=$env:ASSEMBLY_VERSION ` + /p:FileVersion=$env:ASSEMBLY_VERSION ` + /p:AssemblyInformationalVersion=$env:FULLVERSION ` + --self-contained + + - name: Build ARM64 + run: | + dotnet publish WindowsEdgeLight/WindowsEdgeLight.csproj ` + -c Release ` + -r win-arm64 ` + /p:DebugType=None ` + /p:DebugSymbols=false ` + /p:Version=$env:VERSION ` + /p:AssemblyVersion=$env:ASSEMBLY_VERSION ` + /p:FileVersion=$env:ASSEMBLY_VERSION ` + /p:AssemblyInformationalVersion=$env:FULLVERSION ` + --self-contained + + - name: Azure Login + uses: azure/login@v2 + with: + creds: '{"clientId":"${{ secrets.AZURE_CLIENT_ID }}","clientSecret":"${{ secrets.AZURE_CLIENT_SECRET }}","subscriptionId":"${{ secrets.AZURE_SUBSCRIPTION_ID }}","tenantId":"${{ secrets.AZURE_TENANT_ID }}"}' + + - name: Sign executables with Trusted Signing + uses: azure/trusted-signing-action@v1 + with: + azure-tenant-id: ${{ secrets.AZURE_TENANT_ID }} + azure-client-id: ${{ secrets.AZURE_CLIENT_ID }} + azure-client-secret: ${{ secrets.AZURE_CLIENT_SECRET }} + endpoint: https://wus2.codesigning.azure.net/ + signing-account-name: hanselman + certificate-profile-name: WindowsEdgeLight + files-folder: ${{ github.workspace }}\WindowsEdgeLight\bin\Release\net10.0-windows + files-folder-filter: exe + files-folder-recurse: true + file-digest: SHA256 + timestamp-rfc3161: http://timestamp.acs.microsoft.com + timestamp-digest: SHA256 + + - name: Prepare artifacts + shell: pwsh + run: | + New-Item -ItemType Directory -Path artifacts -Force + # Use VERSION environment variable (calculated via GitVersion) + $version = $env:VERSION + + # Create ZIP files with exe and README (so Updatum treats as portable app) + New-Item -ItemType Directory -Path "temp-x64" -Force + Copy-Item "WindowsEdgeLight/bin/Release/net10.0-windows/win-x64/publish/WindowsEdgeLight.exe" -Destination "temp-x64/" + Copy-Item "README.md" -Destination "temp-x64/" + Compress-Archive -Path "temp-x64/*" -DestinationPath "artifacts/WindowsEdgeLight-v$version-win-x64.zip" + + New-Item -ItemType Directory -Path "temp-arm64" -Force + Copy-Item "WindowsEdgeLight/bin/Release/net10.0-windows/win-arm64/publish/WindowsEdgeLight.exe" -Destination "temp-arm64/" + Copy-Item "README.md" -Destination "temp-arm64/" + Compress-Archive -Path "temp-arm64/*" -DestinationPath "artifacts/WindowsEdgeLight-v$version-win-arm64.zip" + + Remove-Item "temp-x64" -Recurse -Force + Remove-Item "temp-arm64" -Recurse -Force + + - name: Upload artifacts + uses: actions/upload-artifact@v4 + with: + name: WindowsEdgeLight-Release + path: artifacts/*.zip + + - name: Create Release + if: startsWith(github.ref, 'refs/tags/') + uses: softprops/action-gh-release@v2 + with: + files: artifacts/*.zip + generate_release_notes: true + body: | + ## Windows Edge Light ${{ github.ref_name }} + + ### 📦 Downloads + + | File | Platform | + |------|----------| + | `WindowsEdgeLight-${{ github.ref_name }}-win-x64.zip` | Intel/AMD 64-bit Windows | + | `WindowsEdgeLight-${{ github.ref_name }}-win-arm64.zip` | ARM64 Windows (Surface Pro X, etc.) | + + **Self-contained** - Extract and run, no .NET installation required. + + ### ⌨️ Keyboard Shortcuts + - `Ctrl+Shift+L` - Toggle light on/off + - `Ctrl+Shift+↑` - Increase brightness + - `Ctrl+Shift+↓` - Decrease brightness + + --- + append_body: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6813664..ee00e6a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,44 +1,44 @@ -name: CI - -on: - pull_request: - push: - branches: - - master - -permissions: - contents: read - -concurrency: - group: ci-${{ github.ref }} - cancel-in-progress: true - -jobs: - build-and-test: - runs-on: windows-latest - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: '10.0.x' - - - name: Cache NuGet packages - uses: actions/cache@v4 - with: - path: ~\.nuget\packages - key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }} - restore-keys: | - ${{ runner.os }}-nuget- - - - name: Restore - run: dotnet restore WindowsEdgeLight.sln - - - name: Build - run: dotnet build WindowsEdgeLight.sln --configuration Release --no-restore - - - name: Test - run: dotnet test WindowsEdgeLight.sln --configuration Release --no-build +name: CI + +on: + pull_request: + push: + branches: + - master + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-and-test: + runs-on: windows-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Cache NuGet packages + uses: actions/cache@v4 + with: + path: ~\.nuget\packages + key: ${{ runner.os }}-nuget-${{ hashFiles('**/*.csproj') }} + restore-keys: | + ${{ runner.os }}-nuget- + + - name: Restore + run: dotnet restore WindowsEdgeLight.sln + + - name: Build + run: dotnet build WindowsEdgeLight.sln --configuration Release --no-restore + + - name: Test + run: dotnet test WindowsEdgeLight.sln --configuration Release --no-build diff --git a/README.md b/README.md index d0cd90b..db54400 100644 --- a/README.md +++ b/README.md @@ -1,205 +1,205 @@ -# Windows Edge Light - -A lightweight WPF application that adds a customizable glowing edge light effect around your monitors on Windows. Perfect for ambient lighting during video calls, streaming, or just adding a professional touch to your workspace. - -## Features - -- **Automatic Updates**: Built-in update system checks GitHub Releases for new versions -- **Multi-Monitor Support**: Display on your primary monitor, switch to another monitor, or show on all monitors simultaneously -- **DPI Aware**: Properly handles high-DPI displays (4K monitors with scaling) -- **Fluent Design**: Modern UX that fits in with the Windows look and feel -- **Click-Through Transparency**: Overlay doesn't interfere with your work - all clicks pass through to applications beneath -- **Customizable Brightness**: Adjust opacity with easy-to-use controls -- **Adjustable Color Temperature**: Shift the edge light from cooler (blue-ish) to warmer (amber) tones -- **Toggle On/Off**: Quickly enable or disable the edge light effect -- **Hideable Controls**: Hide the control toolbar for a cleaner look, restore via tray menu -- **Always On Top**: Stays visible above all other windows -- **Persistent Settings**: Brightness, color temperature, on/off state, and preferences are saved across restarts -- **Settings Window**: Dedicated settings panel with sliders and control-bar customization -- **Exclude from Screen Capture**: Optional setting to hide the edge light from screen sharing (Teams, Zoom) and screenshots -- **Keyboard Shortcuts**: - - `Ctrl+Shift+L` - Toggle light on/off - - `Ctrl+Shift+Up` - Increase brightness - - `Ctrl+Shift+Down` - Decrease brightness -- **Gradient Effect**: Beautiful white gradient with subtle blur for a professional look - -## Screenshots - -The application creates a smooth, glowing border around the edges of your primary monitor: - -- Adjustable brightness levels (20% to 100% opacity) -- Soft blur effect for a natural glow -- Minimal UI controls that fade in on hover - -![Windows Edge Light](HeroImage.png) - -## Installation - -### Option 1: Download Pre-built Executable - -Download the latest `WindowsEdgeLight.exe` from the [Releases page](https://github.com/shanselman/WindowsEdgeLight/releases). This is a single-file executable that includes everything you need - no .NET installation required! - -### Option 2: Build from Source - -#### Prerequisites - -- Windows 10 or later -- .NET 10.0 SDK for building - -#### Building from Source - -1. Clone this repository: - ```bash - git clone https://github.com/shanselman/WindowsEdgeLight.git - cd WindowsEdgeLight - ``` - -2. Build the project: - ```bash - cd WindowsEdgeLight - dotnet build - ``` - -3. Run the application: - ```bash - dotnet run - ``` - -#### Creating a Single-File Executable - -To create a standalone executable: -```bash -cd WindowsEdgeLight -dotnet publish -c Release /p:DebugType=None /p:DebugSymbols=false -``` - -The executable will be in `bin\Release\net10.0-windows\win-x64\publish\WindowsEdgeLight.exe` - -**Note**: WPF applications cannot use AOT compilation or aggressive trimming. The single-file executable is self-contained and compressed (~72MB) but includes the full .NET runtime. - -## Usage - -1. Launch `WindowsEdgeLight.exe` -2. The edge light will appear around your primary monitor -3. Control toolbar appears at the bottom center with these buttons: - - 🔅 **Decrease Brightness** - Reduces opacity - - 🔆 **Increase Brightness** - Increases opacity - - 🔥 **Warmer Color** - Shifts the glow towards a warmer, amber tone - - ❄️ **Cooler Color** - Shifts the glow towards a cooler, blue-ish white - - 💡 **Toggle Light** - Turn the effect on/off - - 🖥️ **Switch Monitor** - Move to next monitor (if multiple monitors) - - 🖥️🖥️ **All Monitors** - Show on all monitors (if multiple monitors) - - ⚙️ **Settings** - Adjust appearance, capture exclusion, and control visibility - - ✖ **Exit** - Close the application -4. Hide the control toolbar for a cleaner look using the tray menu (right-click tray icon → "Hide Controls") - -### Screen Sharing Mode - -When sharing your screen on video conferencing apps (Teams, Zoom, etc.), you may want the edge light to be visible to you but invisible to viewers. Enable **"Exclude from Screen Capture"** via: -- Open ⚙️ **Settings** from the control toolbar and enable **Exclude from Screen Capture**, or -- Right-click the tray icon → "Exclude from Screen Capture" - -**Note**: When this setting is enabled, the edge light will also be excluded from screenshots taken with Windows Snipping Tool, PrintScreen, or other capture tools. - -### Keyboard Shortcuts - -- **Ctrl+Shift+L**: Toggle the edge light on/off -- **Ctrl+Shift+Up**: Increase brightness -- **Ctrl+Shift+Down**: Decrease brightness -- **Taskbar**: Right-click the taskbar icon for a menu with toggle, brightness, and color temperature controls - -## Technical Details - -### Architecture - -- **Framework**: .NET 10.0 WPF (Windows Presentation Foundation) -- **Language**: C# -- **UI**: XAML with transparent window overlay -- **Monitor Detection**: Windows Forms Screen API for accurate multi-monitor support - -### Key Features Implementation - -- **Click-Through**: Uses Win32 `WS_EX_TRANSPARENT` and `WS_EX_LAYERED` window styles -- **DPI Scaling**: Converts physical pixels to WPF Device Independent Pixels for proper sizing -- **Primary Monitor**: Uses `Screen.PrimaryScreen.Bounds` with DPI correction -- **Gradient Border**: Custom Rectangle with LinearGradientBrush and BlurEffect - -## Multi-Monitor Support - -The application supports flexible multi-monitor configurations: -- Starts on the primary monitor -- Switches between connected monitors from the toolbar or tray menu -- Can display the edge light on every connected monitor simultaneously -- Handles per-monitor DPI scaling and mixed monitor arrangements - -## Development - -### Project Structure - -``` -WindowsEdgeLight/ -├── WindowsEdgeLight/ -│ ├── App.xaml # Application entry point -│ ├── App.xaml.cs -│ ├── MainWindow.xaml # Main UI layout -│ ├── MainWindow.xaml.cs # Application logic -│ ├── WindowsEdgeLight.csproj -│ └── AssemblyInfo.cs -└── README.md -``` - -### Building - -Requires: -- Visual Studio 2022 or later (with .NET desktop development workload) -- Or .NET 10.0 SDK for command-line builds - -## Version History - -**Note**: Versions are automatically managed using GitVersion based on Git tags. - -### v0.6 - Automatic Update System -- Integrated Updatum for automatic updates from GitHub Releases -- Beautiful update dialog with release notes -- Download progress tracking -- One-click install for new versions -- See [UPDATUM_INTEGRATION.md](UPDATUM_INTEGRATION.md) for details - -### v0.3 - Global Hotkeys and Taskbar Support -- Added global hotkeys for brightness control (Ctrl+Shift+Up/Down) -- Fixed taskbar overlap - window now respects taskbar area -- Added taskbar icon for easy right-click close -- Removed conflicting exit hotkey -- Added custom ring light icon -- Added assembly information with author details - -### v0.2 - Primary Monitor Display Fix -- Fixed window to display on primary monitor only -- Added proper DPI scaling support for high-resolution displays -- Resolved namespace conflicts with Windows Forms integration -- Improved multi-monitor setup compatibility - -### v0.1 - Initial Release -- Basic edge light overlay functionality -- Customizable brightness controls -- Toggle and keyboard shortcut support -- Click-through transparency - -## License - -This project is provided as-is for personal and educational use. - -## Contributing - -Contributions are welcome! Feel free to: -- Report bugs -- Suggest new features -- Submit pull requests - -## Acknowledgments - -Inspired by the need for professional lighting effects during video conferences and streaming setups. - ---- - -**Note**: This application is designed for Windows only and requires the .NET 10.0 runtime. +# Windows Edge Light + +A lightweight WPF application that adds a customizable glowing edge light effect around your monitors on Windows. Perfect for ambient lighting during video calls, streaming, or just adding a professional touch to your workspace. + +## Features + +- **Automatic Updates**: Built-in update system checks GitHub Releases for new versions +- **Multi-Monitor Support**: Display on your primary monitor, switch to another monitor, or show on all monitors simultaneously +- **DPI Aware**: Properly handles high-DPI displays (4K monitors with scaling) +- **Fluent Design**: Modern UX that fits in with the Windows look and feel +- **Click-Through Transparency**: Overlay doesn't interfere with your work - all clicks pass through to applications beneath +- **Customizable Brightness**: Adjust opacity with easy-to-use controls +- **Adjustable Color Temperature**: Shift the edge light from cooler (blue-ish) to warmer (amber) tones +- **Toggle On/Off**: Quickly enable or disable the edge light effect +- **Hideable Controls**: Hide the control toolbar for a cleaner look, restore via tray menu +- **Always On Top**: Stays visible above all other windows +- **Persistent Settings**: Brightness, color temperature, on/off state, and preferences are saved across restarts +- **Settings Window**: Dedicated settings panel with sliders and control-bar customization +- **Exclude from Screen Capture**: Optional setting to hide the edge light from screen sharing (Teams, Zoom) and screenshots +- **Keyboard Shortcuts**: + - `Ctrl+Shift+L` - Toggle light on/off + - `Ctrl+Shift+Up` - Increase brightness + - `Ctrl+Shift+Down` - Decrease brightness +- **Gradient Effect**: Beautiful white gradient with subtle blur for a professional look + +## Screenshots + +The application creates a smooth, glowing border around the edges of your primary monitor: + +- Adjustable brightness levels (20% to 100% opacity) +- Soft blur effect for a natural glow +- Minimal UI controls that fade in on hover + +![Windows Edge Light](HeroImage.png) + +## Installation + +### Option 1: Download Pre-built Executable + +Download the latest `WindowsEdgeLight.exe` from the [Releases page](https://github.com/shanselman/WindowsEdgeLight/releases). This is a single-file executable that includes everything you need - no .NET installation required! + +### Option 2: Build from Source + +#### Prerequisites + +- Windows 10 or later +- .NET 10.0 SDK for building + +#### Building from Source + +1. Clone this repository: + ```bash + git clone https://github.com/shanselman/WindowsEdgeLight.git + cd WindowsEdgeLight + ``` + +2. Build the project: + ```bash + cd WindowsEdgeLight + dotnet build + ``` + +3. Run the application: + ```bash + dotnet run + ``` + +#### Creating a Single-File Executable + +To create a standalone executable: +```bash +cd WindowsEdgeLight +dotnet publish -c Release /p:DebugType=None /p:DebugSymbols=false +``` + +The executable will be in `bin\Release\net10.0-windows\win-x64\publish\WindowsEdgeLight.exe` + +**Note**: WPF applications cannot use AOT compilation or aggressive trimming. The single-file executable is self-contained and compressed (~72MB) but includes the full .NET runtime. + +## Usage + +1. Launch `WindowsEdgeLight.exe` +2. The edge light will appear around your primary monitor +3. Control toolbar appears at the bottom center with these buttons: + - 🔅 **Decrease Brightness** - Reduces opacity + - 🔆 **Increase Brightness** - Increases opacity + - 🔥 **Warmer Color** - Shifts the glow towards a warmer, amber tone + - ❄️ **Cooler Color** - Shifts the glow towards a cooler, blue-ish white + - 💡 **Toggle Light** - Turn the effect on/off + - 🖥️ **Switch Monitor** - Move to next monitor (if multiple monitors) + - 🖥️🖥️ **All Monitors** - Show on all monitors (if multiple monitors) + - ⚙️ **Settings** - Adjust appearance, capture exclusion, and control visibility + - ✖ **Exit** - Close the application +4. Hide the control toolbar for a cleaner look using the tray menu (right-click tray icon → "Hide Controls") + +### Screen Sharing Mode + +When sharing your screen on video conferencing apps (Teams, Zoom, etc.), you may want the edge light to be visible to you but invisible to viewers. Enable **"Exclude from Screen Capture"** via: +- Open ⚙️ **Settings** from the control toolbar and enable **Exclude from Screen Capture**, or +- Right-click the tray icon → "Exclude from Screen Capture" + +**Note**: When this setting is enabled, the edge light will also be excluded from screenshots taken with Windows Snipping Tool, PrintScreen, or other capture tools. + +### Keyboard Shortcuts + +- **Ctrl+Shift+L**: Toggle the edge light on/off +- **Ctrl+Shift+Up**: Increase brightness +- **Ctrl+Shift+Down**: Decrease brightness +- **Taskbar**: Right-click the taskbar icon for a menu with toggle, brightness, and color temperature controls + +## Technical Details + +### Architecture + +- **Framework**: .NET 10.0 WPF (Windows Presentation Foundation) +- **Language**: C# +- **UI**: XAML with transparent window overlay +- **Monitor Detection**: Windows Forms Screen API for accurate multi-monitor support + +### Key Features Implementation + +- **Click-Through**: Uses Win32 `WS_EX_TRANSPARENT` and `WS_EX_LAYERED` window styles +- **DPI Scaling**: Converts physical pixels to WPF Device Independent Pixels for proper sizing +- **Primary Monitor**: Uses `Screen.PrimaryScreen.Bounds` with DPI correction +- **Gradient Border**: Custom Rectangle with LinearGradientBrush and BlurEffect + +## Multi-Monitor Support + +The application supports flexible multi-monitor configurations: +- Starts on the primary monitor +- Switches between connected monitors from the toolbar or tray menu +- Can display the edge light on every connected monitor simultaneously +- Handles per-monitor DPI scaling and mixed monitor arrangements + +## Development + +### Project Structure + +``` +WindowsEdgeLight/ +├── WindowsEdgeLight/ +│ ├── App.xaml # Application entry point +│ ├── App.xaml.cs +│ ├── MainWindow.xaml # Main UI layout +│ ├── MainWindow.xaml.cs # Application logic +│ ├── WindowsEdgeLight.csproj +│ └── AssemblyInfo.cs +└── README.md +``` + +### Building + +Requires: +- Visual Studio 2022 or later (with .NET desktop development workload) +- Or .NET 10.0 SDK for command-line builds + +## Version History + +**Note**: Versions are automatically managed using GitVersion based on Git tags. + +### v0.6 - Automatic Update System +- Integrated Updatum for automatic updates from GitHub Releases +- Beautiful update dialog with release notes +- Download progress tracking +- One-click install for new versions +- See [UPDATUM_INTEGRATION.md](UPDATUM_INTEGRATION.md) for details + +### v0.3 - Global Hotkeys and Taskbar Support +- Added global hotkeys for brightness control (Ctrl+Shift+Up/Down) +- Fixed taskbar overlap - window now respects taskbar area +- Added taskbar icon for easy right-click close +- Removed conflicting exit hotkey +- Added custom ring light icon +- Added assembly information with author details + +### v0.2 - Primary Monitor Display Fix +- Fixed window to display on primary monitor only +- Added proper DPI scaling support for high-resolution displays +- Resolved namespace conflicts with Windows Forms integration +- Improved multi-monitor setup compatibility + +### v0.1 - Initial Release +- Basic edge light overlay functionality +- Customizable brightness controls +- Toggle and keyboard shortcut support +- Click-through transparency + +## License + +This project is provided as-is for personal and educational use. + +## Contributing + +Contributions are welcome! Feel free to: +- Report bugs +- Suggest new features +- Submit pull requests + +## Acknowledgments + +Inspired by the need for professional lighting effects during video conferences and streaming setups. + +--- + +**Note**: This application is designed for Windows only and requires the .NET 10.0 runtime. diff --git a/WindowsEdgeLight.Tests/AppSettingsTests.cs b/WindowsEdgeLight.Tests/AppSettingsTests.cs index 35bc3a0..364696f 100644 --- a/WindowsEdgeLight.Tests/AppSettingsTests.cs +++ b/WindowsEdgeLight.Tests/AppSettingsTests.cs @@ -1,137 +1,137 @@ -using System.Text.Json; -using Xunit; - -namespace WindowsEdgeLight.Tests; - -public sealed class AppSettingsTests : IDisposable -{ - private readonly string tempDirectory = Path.Combine( - Path.GetTempPath(), - $"WindowsEdgeLight.Tests-{Guid.NewGuid():N}"); - - private string SettingsPath => Path.Combine(tempDirectory, "settings.json"); - - [Fact] - public void DefaultsMatchApplicationDefaults() - { - var settings = new AppSettings(); - - Assert.True(settings.ExcludeFromCapture); - Assert.True(settings.IsLightOn); - Assert.Equal(1.0, settings.Brightness); - Assert.Equal(0.5, settings.ColorTemperature); - Assert.True(settings.ShowToggleButton); - Assert.True(settings.ShowBrightnessButtons); - Assert.True(settings.ShowColorTempButtons); - Assert.True(settings.ShowMonitorControlButtons); - } - - [Fact] - public void MissingFileReturnsDefaults() - { - var settings = AppSettings.LoadFrom(SettingsPath); - - Assert.Equal(1.0, settings.Brightness); - Assert.True(settings.IsLightOn); - } - - [Fact] - public void SaveAndLoadRoundTripsAllProperties() - { - var expected = new AppSettings - { - ExcludeFromCapture = false, - IsLightOn = false, - Brightness = 0.7, - ColorTemperature = 0.3, - ShowToggleButton = false, - ShowBrightnessButtons = false, - ShowColorTempButtons = false, - ShowMonitorControlButtons = false - }; - - expected.SaveTo(SettingsPath); - var actual = AppSettings.LoadFrom(SettingsPath); - - Assert.Equal(expected.ExcludeFromCapture, actual.ExcludeFromCapture); - Assert.Equal(expected.IsLightOn, actual.IsLightOn); - Assert.Equal(expected.Brightness, actual.Brightness); - Assert.Equal(expected.ColorTemperature, actual.ColorTemperature); - Assert.Equal(expected.ShowToggleButton, actual.ShowToggleButton); - Assert.Equal(expected.ShowBrightnessButtons, actual.ShowBrightnessButtons); - Assert.Equal(expected.ShowColorTempButtons, actual.ShowColorTempButtons); - Assert.Equal(expected.ShowMonitorControlButtons, actual.ShowMonitorControlButtons); - Assert.False(File.Exists(SettingsPath + ".tmp")); - } - - [Fact] - public void SaveReplacesExistingFile() - { - Directory.CreateDirectory(tempDirectory); - File.WriteAllText(SettingsPath, """{"Brightness":0.2}"""); - var settings = new AppSettings { Brightness = 0.8 }; - - settings.SaveTo(SettingsPath); - - Assert.Equal(0.8, AppSettings.LoadFrom(SettingsPath).Brightness); - Assert.False(File.Exists(SettingsPath + ".tmp")); - } - - [Fact] - public void SaveCreatesParentDirectory() - { - var nestedPath = Path.Combine(tempDirectory, "nested", "settings.json"); - - new AppSettings().SaveTo(nestedPath); - - Assert.True(File.Exists(nestedPath)); - } - - [Fact] - public void CorruptJsonReturnsDefaultsAndDeletesFile() - { - Directory.CreateDirectory(tempDirectory); - File.WriteAllText(SettingsPath, "{ invalid"); - - var settings = AppSettings.LoadFrom(SettingsPath); - - Assert.Equal(1.0, settings.Brightness); - Assert.False(File.Exists(SettingsPath)); - } - - [Fact] - public void CommentsAndTrailingCommasAreAccepted() - { - Directory.CreateDirectory(tempDirectory); - File.WriteAllText(SettingsPath, """ - { - // User-edited settings remain supported. - "Brightness": 0.6, - "ColorTemperature": 0.2, - } - """); - - var settings = AppSettings.LoadFrom(SettingsPath); - - Assert.Equal(0.6, settings.Brightness); - Assert.Equal(0.2, settings.ColorTemperature); - } - - [Fact] - public void SavedJsonIsIndented() - { - new AppSettings().SaveTo(SettingsPath); - - var json = File.ReadAllText(SettingsPath); - Assert.Contains(Environment.NewLine, json); - Assert.NotNull(JsonSerializer.Deserialize(json)); - } - - public void Dispose() - { - if (Directory.Exists(tempDirectory)) - { - Directory.Delete(tempDirectory, recursive: true); - } - } -} +using System.Text.Json; +using Xunit; + +namespace WindowsEdgeLight.Tests; + +public sealed class AppSettingsTests : IDisposable +{ + private readonly string tempDirectory = Path.Combine( + Path.GetTempPath(), + $"WindowsEdgeLight.Tests-{Guid.NewGuid():N}"); + + private string SettingsPath => Path.Combine(tempDirectory, "settings.json"); + + [Fact] + public void DefaultsMatchApplicationDefaults() + { + var settings = new AppSettings(); + + Assert.True(settings.ExcludeFromCapture); + Assert.True(settings.IsLightOn); + Assert.Equal(1.0, settings.Brightness); + Assert.Equal(0.5, settings.ColorTemperature); + Assert.True(settings.ShowToggleButton); + Assert.True(settings.ShowBrightnessButtons); + Assert.True(settings.ShowColorTempButtons); + Assert.True(settings.ShowMonitorControlButtons); + } + + [Fact] + public void MissingFileReturnsDefaults() + { + var settings = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(1.0, settings.Brightness); + Assert.True(settings.IsLightOn); + } + + [Fact] + public void SaveAndLoadRoundTripsAllProperties() + { + var expected = new AppSettings + { + ExcludeFromCapture = false, + IsLightOn = false, + Brightness = 0.7, + ColorTemperature = 0.3, + ShowToggleButton = false, + ShowBrightnessButtons = false, + ShowColorTempButtons = false, + ShowMonitorControlButtons = false + }; + + expected.SaveTo(SettingsPath); + var actual = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(expected.ExcludeFromCapture, actual.ExcludeFromCapture); + Assert.Equal(expected.IsLightOn, actual.IsLightOn); + Assert.Equal(expected.Brightness, actual.Brightness); + Assert.Equal(expected.ColorTemperature, actual.ColorTemperature); + Assert.Equal(expected.ShowToggleButton, actual.ShowToggleButton); + Assert.Equal(expected.ShowBrightnessButtons, actual.ShowBrightnessButtons); + Assert.Equal(expected.ShowColorTempButtons, actual.ShowColorTempButtons); + Assert.Equal(expected.ShowMonitorControlButtons, actual.ShowMonitorControlButtons); + Assert.False(File.Exists(SettingsPath + ".tmp")); + } + + [Fact] + public void SaveReplacesExistingFile() + { + Directory.CreateDirectory(tempDirectory); + File.WriteAllText(SettingsPath, """{"Brightness":0.2}"""); + var settings = new AppSettings { Brightness = 0.8 }; + + settings.SaveTo(SettingsPath); + + Assert.Equal(0.8, AppSettings.LoadFrom(SettingsPath).Brightness); + Assert.False(File.Exists(SettingsPath + ".tmp")); + } + + [Fact] + public void SaveCreatesParentDirectory() + { + var nestedPath = Path.Combine(tempDirectory, "nested", "settings.json"); + + new AppSettings().SaveTo(nestedPath); + + Assert.True(File.Exists(nestedPath)); + } + + [Fact] + public void CorruptJsonReturnsDefaultsAndDeletesFile() + { + Directory.CreateDirectory(tempDirectory); + File.WriteAllText(SettingsPath, "{ invalid"); + + var settings = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(1.0, settings.Brightness); + Assert.False(File.Exists(SettingsPath)); + } + + [Fact] + public void CommentsAndTrailingCommasAreAccepted() + { + Directory.CreateDirectory(tempDirectory); + File.WriteAllText(SettingsPath, """ + { + // User-edited settings remain supported. + "Brightness": 0.6, + "ColorTemperature": 0.2, + } + """); + + var settings = AppSettings.LoadFrom(SettingsPath); + + Assert.Equal(0.6, settings.Brightness); + Assert.Equal(0.2, settings.ColorTemperature); + } + + [Fact] + public void SavedJsonIsIndented() + { + new AppSettings().SaveTo(SettingsPath); + + var json = File.ReadAllText(SettingsPath); + Assert.Contains(Environment.NewLine, json); + Assert.NotNull(JsonSerializer.Deserialize(json)); + } + + public void Dispose() + { + if (Directory.Exists(tempDirectory)) + { + Directory.Delete(tempDirectory, recursive: true); + } + } +} diff --git a/WindowsEdgeLight.Tests/WindowsEdgeLight.Tests.csproj b/WindowsEdgeLight.Tests/WindowsEdgeLight.Tests.csproj index ffef641..83d8c41 100644 --- a/WindowsEdgeLight.Tests/WindowsEdgeLight.Tests.csproj +++ b/WindowsEdgeLight.Tests/WindowsEdgeLight.Tests.csproj @@ -1,24 +1,24 @@ - - - - net10.0-windows - enable - enable - false - true - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - + + + + net10.0-windows + enable + enable + false + true + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/WindowsEdgeLight.sln b/WindowsEdgeLight.sln index 44ffdf8..e3bb4df 100644 --- a/WindowsEdgeLight.sln +++ b/WindowsEdgeLight.sln @@ -1,30 +1,30 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.5.2.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsEdgeLight", "WindowsEdgeLight\WindowsEdgeLight.csproj", "{C2187EC4-5511-1F4A-A7C5-D7D114D039DC}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsEdgeLight.Tests", "WindowsEdgeLight.Tests\WindowsEdgeLight.Tests.csproj", "{B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Release|Any CPU.Build.0 = Release|Any CPU - {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {A907C696-8323-4246-BE77-DEBB79E9D8A5} - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.2.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsEdgeLight", "WindowsEdgeLight\WindowsEdgeLight.csproj", "{C2187EC4-5511-1F4A-A7C5-D7D114D039DC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WindowsEdgeLight.Tests", "WindowsEdgeLight.Tests\WindowsEdgeLight.Tests.csproj", "{B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C2187EC4-5511-1F4A-A7C5-D7D114D039DC}.Release|Any CPU.Build.0 = Release|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B1E2F3A4-6622-2F5B-B8D6-E8E225E04AED}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A907C696-8323-4246-BE77-DEBB79E9D8A5} + EndGlobalSection +EndGlobal diff --git a/WindowsEdgeLight/AppSettings.cs b/WindowsEdgeLight/AppSettings.cs index eab3547..547091e 100644 --- a/WindowsEdgeLight/AppSettings.cs +++ b/WindowsEdgeLight/AppSettings.cs @@ -1,137 +1,137 @@ -using System; -using System.IO; -using System.Text.Json; - -namespace WindowsEdgeLight; - -/// -/// Application settings that persist across sessions -/// -public class AppSettings -{ - private static readonly string SettingsFilePath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "WindowsEdgeLight", - "settings.json"); - - private static readonly JsonSerializerOptions ReadOptions = new() - { - AllowTrailingCommas = true, - ReadCommentHandling = JsonCommentHandling.Skip - }; - - private static readonly JsonSerializerOptions WriteOptions = new() - { - WriteIndented = true - }; - - /// - /// When enabled, excludes the edge light from screen capture (Teams, screenshots, etc.) - /// Note: When enabled, screenshots won't capture the edge light effect - /// - public bool ExcludeFromCapture { get; set; } = true; - - /// - /// Whether the edge light is on or off (persisted across restarts) - /// - public bool IsLightOn { get; set; } = true; - - /// - /// Brightness/opacity of the edge light, in the range [0.2, 1.0] - /// - public double Brightness { get; set; } = 1.0; - - /// - /// Color temperature of the edge light, in the range [0.0, 1.0] - /// where 0.0 = coolest (blue-white) and 1.0 = warmest (amber) - /// - public double ColorTemperature { get; set; } = 0.5; - - /// - /// Whether to show toggle button in the control window - /// - public bool ShowToggleButton { get; set; } = true; - - /// - /// Whether to show brightness buttons in the control window - /// - public bool ShowBrightnessButtons { get; set; } = true; - - /// - /// Whether to show color temperature buttons in the control window - /// - public bool ShowColorTempButtons { get; set; } = true; - - /// - /// Whether to show window control buttons (toggle, switch monitor, all monitors) in the control window - /// - public bool ShowMonitorControlButtons { get; set; } = true; - - /// - /// Load settings from disk - /// - public static AppSettings Load() => LoadFrom(SettingsFilePath); - - internal static AppSettings LoadFrom(string filePath) - { - try - { - if (File.Exists(filePath)) - { - var json = File.ReadAllText(filePath); - var settings = JsonSerializer.Deserialize(json, ReadOptions); - - // Validate deserialized settings - if (settings != null) - { - return settings; - } - } - } - catch (JsonException ex) - { - System.Diagnostics.Debug.WriteLine($"Failed to parse settings file: {ex.Message}"); - // Delete corrupted settings file - try - { - if (File.Exists(filePath)) - { - File.Delete(filePath); - } - } - catch { /* Ignore deletion errors */ } - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine($"Failed to load settings: {ex.Message}"); - } - - return new AppSettings(); - } - - /// - /// Save settings to disk - /// - public void Save() => SaveTo(SettingsFilePath); - - internal void SaveTo(string filePath) - { - try - { - var directory = Path.GetDirectoryName(filePath); - if (directory != null && !Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } - - var json = JsonSerializer.Serialize(this, WriteOptions); - var tempPath = filePath + ".tmp"; - File.WriteAllText(tempPath, json); - File.Move(tempPath, filePath, overwrite: true); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine($"Failed to save settings: {ex.Message}"); - } - } -} +using System; +using System.IO; +using System.Text.Json; + +namespace WindowsEdgeLight; + +/// +/// Application settings that persist across sessions +/// +public class AppSettings +{ + private static readonly string SettingsFilePath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "WindowsEdgeLight", + "settings.json"); + + private static readonly JsonSerializerOptions ReadOptions = new() + { + AllowTrailingCommas = true, + ReadCommentHandling = JsonCommentHandling.Skip + }; + + private static readonly JsonSerializerOptions WriteOptions = new() + { + WriteIndented = true + }; + + /// + /// When enabled, excludes the edge light from screen capture (Teams, screenshots, etc.) + /// Note: When enabled, screenshots won't capture the edge light effect + /// + public bool ExcludeFromCapture { get; set; } = true; + + /// + /// Whether the edge light is on or off (persisted across restarts) + /// + public bool IsLightOn { get; set; } = true; + + /// + /// Brightness/opacity of the edge light, in the range [0.2, 1.0] + /// + public double Brightness { get; set; } = 1.0; + + /// + /// Color temperature of the edge light, in the range [0.0, 1.0] + /// where 0.0 = coolest (blue-white) and 1.0 = warmest (amber) + /// + public double ColorTemperature { get; set; } = 0.5; + + /// + /// Whether to show toggle button in the control window + /// + public bool ShowToggleButton { get; set; } = true; + + /// + /// Whether to show brightness buttons in the control window + /// + public bool ShowBrightnessButtons { get; set; } = true; + + /// + /// Whether to show color temperature buttons in the control window + /// + public bool ShowColorTempButtons { get; set; } = true; + + /// + /// Whether to show window control buttons (toggle, switch monitor, all monitors) in the control window + /// + public bool ShowMonitorControlButtons { get; set; } = true; + + /// + /// Load settings from disk + /// + public static AppSettings Load() => LoadFrom(SettingsFilePath); + + internal static AppSettings LoadFrom(string filePath) + { + try + { + if (File.Exists(filePath)) + { + var json = File.ReadAllText(filePath); + var settings = JsonSerializer.Deserialize(json, ReadOptions); + + // Validate deserialized settings + if (settings != null) + { + return settings; + } + } + } + catch (JsonException ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to parse settings file: {ex.Message}"); + // Delete corrupted settings file + try + { + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + } + catch { /* Ignore deletion errors */ } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to load settings: {ex.Message}"); + } + + return new AppSettings(); + } + + /// + /// Save settings to disk + /// + public void Save() => SaveTo(SettingsFilePath); + + internal void SaveTo(string filePath) + { + try + { + var directory = Path.GetDirectoryName(filePath); + if (directory != null && !Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + + var json = JsonSerializer.Serialize(this, WriteOptions); + var tempPath = filePath + ".tmp"; + File.WriteAllText(tempPath, json); + File.Move(tempPath, filePath, overwrite: true); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Failed to save settings: {ex.Message}"); + } + } +} diff --git a/WindowsEdgeLight/AssemblyInfo.cs b/WindowsEdgeLight/AssemblyInfo.cs index fa836ed..664c931 100644 --- a/WindowsEdgeLight/AssemblyInfo.cs +++ b/WindowsEdgeLight/AssemblyInfo.cs @@ -1,13 +1,13 @@ -using System.Windows; -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("WindowsEdgeLight.Tests")] - -[assembly:ThemeInfo( - ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, - // or application resource dictionaries) - ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, - // app, or any theme specific resource dictionaries) -)] +using System.Windows; +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("WindowsEdgeLight.Tests")] + +[assembly:ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/WindowsEdgeLight/ControlWindow.xaml.cs b/WindowsEdgeLight/ControlWindow.xaml.cs index 49e0f56..3509199 100644 --- a/WindowsEdgeLight/ControlWindow.xaml.cs +++ b/WindowsEdgeLight/ControlWindow.xaml.cs @@ -1,119 +1,119 @@ -using System.Windows; -using System.Windows.Input; - -namespace WindowsEdgeLight; - -public partial class ControlWindow : Window -{ - private readonly MainWindow mainWindow; - - public ControlWindow(MainWindow main) - { - InitializeComponent(); - mainWindow = main; - - UpdateMonitorButtonState(); - ApplyButtonVisibility(); - } - - private void UpdateMonitorButtonState() - { - SwitchMonitorButton.IsEnabled = mainWindow.HasMultipleMonitors() && !mainWindow.IsShowingOnAllMonitors(); - AllMonitorsButton.IsEnabled = mainWindow.HasMultipleMonitors(); - } - - public void ApplyButtonVisibility() - { - var toggleButtonVis = mainWindow.GetIsToggleButtonVisible() ? Visibility.Visible : Visibility.Collapsed; - var brightVis = mainWindow.GetIsBrightnessButtonsVisible() ? Visibility.Visible : Visibility.Collapsed; - var tempVis = mainWindow.GetIsColorTempButtonsVisible() ? Visibility.Visible : Visibility.Collapsed; - var monitorCtrlVis = mainWindow.GetIsControlMonitorsButtonVisible() ? Visibility.Visible : Visibility.Collapsed; - - ToggleLightButton.Visibility = toggleButtonVis; - BrightnessDownButton.Visibility = brightVis; - BrightnessUpButton.Visibility = brightVis; - ColorWarmerButton.Visibility = tempVis; - ColorCoolerButton.Visibility = tempVis; - SwitchMonitorButton.Visibility = monitorCtrlVis; - AllMonitorsButton.Visibility = monitorCtrlVis; - } - - public void UpdateAllMonitorsButtonState() - { - UpdateMonitorButtonState(); - } - - private void BrightnessDown_Click(object sender, RoutedEventArgs e) - { - mainWindow.DecreaseBrightness(); - } - - private void BrightnessUp_Click(object sender, RoutedEventArgs e) - { - mainWindow.IncreaseBrightness(); - } - - private void ColorCooler_Click(object sender, RoutedEventArgs e) - { - mainWindow.DecreaseColorTemperature(); - } - - private void ColorWarmer_Click(object sender, RoutedEventArgs e) - { - mainWindow.IncreaseColorTemperature(); - } - - private void Toggle_Click(object sender, RoutedEventArgs e) - { - mainWindow.HandleToggle(); - } - - private void SwitchMonitor_Click(object sender, RoutedEventArgs e) - { - mainWindow.MoveToNextMonitor(); - UpdateMonitorButtonState(); - } - - private void AllMonitors_Click(object sender, RoutedEventArgs e) - { - mainWindow.ToggleAllMonitors(); - } - - private void Open_Settings(object sender, RoutedEventArgs e) - { - var settings = new SettingsWindow(mainWindow); - settings.Owner = this; - settings.ShowDialog(); - ApplyButtonVisibility(); - } - - private void DragHandle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) - { - if (e.LeftButton != MouseButtonState.Pressed) - { - return; - } - - var initialLeft = Left; - var initialTop = Top; - - try - { - DragMove(); - } - catch (System.InvalidOperationException) - { - // DragMove can throw if the mouse button is no longer pressed; ignore. - } - - if (Math.Abs(Left - initialLeft) > 0.5 || Math.Abs(Top - initialTop) > 0.5) - { - mainWindow.NotifyControlWindowManuallyMoved(); - } - } - - private void Close_Click(object sender, RoutedEventArgs e) - { - System.Windows.Application.Current.Shutdown(); - } -} +using System.Windows; +using System.Windows.Input; + +namespace WindowsEdgeLight; + +public partial class ControlWindow : Window +{ + private readonly MainWindow mainWindow; + + public ControlWindow(MainWindow main) + { + InitializeComponent(); + mainWindow = main; + + UpdateMonitorButtonState(); + ApplyButtonVisibility(); + } + + private void UpdateMonitorButtonState() + { + SwitchMonitorButton.IsEnabled = mainWindow.HasMultipleMonitors() && !mainWindow.IsShowingOnAllMonitors(); + AllMonitorsButton.IsEnabled = mainWindow.HasMultipleMonitors(); + } + + public void ApplyButtonVisibility() + { + var toggleButtonVis = mainWindow.GetIsToggleButtonVisible() ? Visibility.Visible : Visibility.Collapsed; + var brightVis = mainWindow.GetIsBrightnessButtonsVisible() ? Visibility.Visible : Visibility.Collapsed; + var tempVis = mainWindow.GetIsColorTempButtonsVisible() ? Visibility.Visible : Visibility.Collapsed; + var monitorCtrlVis = mainWindow.GetIsControlMonitorsButtonVisible() ? Visibility.Visible : Visibility.Collapsed; + + ToggleLightButton.Visibility = toggleButtonVis; + BrightnessDownButton.Visibility = brightVis; + BrightnessUpButton.Visibility = brightVis; + ColorWarmerButton.Visibility = tempVis; + ColorCoolerButton.Visibility = tempVis; + SwitchMonitorButton.Visibility = monitorCtrlVis; + AllMonitorsButton.Visibility = monitorCtrlVis; + } + + public void UpdateAllMonitorsButtonState() + { + UpdateMonitorButtonState(); + } + + private void BrightnessDown_Click(object sender, RoutedEventArgs e) + { + mainWindow.DecreaseBrightness(); + } + + private void BrightnessUp_Click(object sender, RoutedEventArgs e) + { + mainWindow.IncreaseBrightness(); + } + + private void ColorCooler_Click(object sender, RoutedEventArgs e) + { + mainWindow.DecreaseColorTemperature(); + } + + private void ColorWarmer_Click(object sender, RoutedEventArgs e) + { + mainWindow.IncreaseColorTemperature(); + } + + private void Toggle_Click(object sender, RoutedEventArgs e) + { + mainWindow.HandleToggle(); + } + + private void SwitchMonitor_Click(object sender, RoutedEventArgs e) + { + mainWindow.MoveToNextMonitor(); + UpdateMonitorButtonState(); + } + + private void AllMonitors_Click(object sender, RoutedEventArgs e) + { + mainWindow.ToggleAllMonitors(); + } + + private void Open_Settings(object sender, RoutedEventArgs e) + { + var settings = new SettingsWindow(mainWindow); + settings.Owner = this; + settings.ShowDialog(); + ApplyButtonVisibility(); + } + + private void DragHandle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + if (e.LeftButton != MouseButtonState.Pressed) + { + return; + } + + var initialLeft = Left; + var initialTop = Top; + + try + { + DragMove(); + } + catch (System.InvalidOperationException) + { + // DragMove can throw if the mouse button is no longer pressed; ignore. + } + + if (Math.Abs(Left - initialLeft) > 0.5 || Math.Abs(Top - initialTop) > 0.5) + { + mainWindow.NotifyControlWindowManuallyMoved(); + } + } + + private void Close_Click(object sender, RoutedEventArgs e) + { + System.Windows.Application.Current.Shutdown(); + } +} diff --git a/WindowsEdgeLight/MainWindow.xaml.cs b/WindowsEdgeLight/MainWindow.xaml.cs index f1a7558..5d517d2 100644 --- a/WindowsEdgeLight/MainWindow.xaml.cs +++ b/WindowsEdgeLight/MainWindow.xaml.cs @@ -1,1473 +1,1473 @@ -using System.IO; -using System.Runtime.InteropServices; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; -using System.Windows.Interop; -using System.Windows.Media; -using System.Windows.Media.Effects; -using System.Windows.Shapes; -using System.Windows.Threading; -using MediaColor = System.Windows.Media.Color; - -namespace WindowsEdgeLight; - -public partial class MainWindow : Window -{ - private bool isLightOn = true; - private double currentOpacity = 1.0; // Full brightness by default - private const double OpacityStep = 0.15; - private const double MinOpacity = 0.2; - private const double MaxOpacity = 1.0; - - - // Color temperature ("cool" blue-ish to "warm" amber-ish) - // We'll model this as a simple 0-1 slider where 0 = coolest, 1 = warmest. - private double _colorTemperature = 0.5; - private const double ColorTempStep = 0.1; - private const double MinColorTemp = 0.0; - private const double MaxColorTemp = 1.0; - - // DPI Scale - private double _dpiScaleX = 1.0; - private double _dpiScaleY = 1.0; - - private bool _isManualMonitorSwitch = false; - - private NotifyIcon? notifyIcon; - private ControlWindow? controlWindow; - // Tracks whether the control window should be visible (controls initial visibility and toggle state) - private bool isControlWindowVisible = true; - // Session-only: once the user drags the control toolbar, stop auto-repositioning it. - private bool controlWindowManuallyMoved = false; - private ToolStripMenuItem? toggleControlsMenuItem; - private ToolStripMenuItem? excludeFromCaptureMenuItem; - - // Application settings - private AppSettings settings = new AppSettings(); - - private sealed class HoleCache - { - public Geometry? BaseGeometry { get; set; } - public EllipseGeometry? Hole { get; set; } - public CombinedGeometry? Combined { get; set; } - } - - private class MonitorWindowContext - { - public Window Window { get; set; } = null!; - public Screen Screen { get; set; } = null!; - public System.Windows.Shapes.Path BorderPath { get; set; } = null!; - public Ellipse HoverRing { get; set; } = null!; - public Geometry BaseGeometry { get; set; } = null!; - public Rect FrameOuterRect { get; set; } - public Rect FrameInnerRect { get; set; } - public double PathOffsetX { get; set; } - public double PathOffsetY { get; set; } - public double DpiScaleX { get; set; } = 1.0; - public double DpiScaleY { get; set; } = 1.0; - public HoleCache HoleCache { get; } = new(); - } - - // Monitor management - private int currentMonitorIndex = 0; - private Screen[] availableMonitors = Array.Empty(); - private bool showOnAllMonitors = false; - private List additionalMonitorWindows = new List(); - - // Global hotkey IDs - private const int HOTKEY_TOGGLE = 1; - private const int HOTKEY_BRIGHTNESS_UP = 2; - private const int HOTKEY_BRIGHTNESS_DOWN = 3; - - [DllImport("user32.dll")] - private static extern int GetSystemMetrics(int nIndex); - private const int SM_CXSCREEN = 0; - private const int SM_CYSCREEN = 1; - - [DllImport("user32.dll")] - private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); - - [DllImport("user32.dll")] - private static extern bool UnregisterHotKey(IntPtr hWnd, int id); - - [DllImport("user32.dll", SetLastError = true)] - private static extern bool SetWindowDisplayAffinity(IntPtr hWnd, uint dwAffinity); - - private const uint WDA_NONE = 0x00000000; - private const uint WDA_EXCLUDEFROMCAPTURE = 0x00000011; - - [DllImport("user32.dll")] - private static extern IntPtr MonitorFromPoint(POINT pt, uint dwFlags); - - [DllImport("shcore.dll")] - private static extern int GetDpiForMonitor(IntPtr hmonitor, int dpiType, out uint dpiX, out uint dpiY); - - private const int MDT_EFFECTIVE_DPI = 0; - private const uint MONITOR_DEFAULTTONEAREST = 2; - - [StructLayout(LayoutKind.Sequential)] - private struct POINT - { - public int x; // lowercase to match existing usage - public int y; - } - - // Mouse hook P/Invoke declarations - [DllImport("user32.dll", SetLastError = true)] - private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId); - - [DllImport("user32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool UnhookWindowsHookEx(IntPtr hhk); - - [DllImport("user32.dll")] - private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); - - [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern IntPtr GetModuleHandle(string lpModuleName); - - private const int WH_MOUSE_LL = 14; - private const int WM_MOUSEMOVE = 0x0200; - - [StructLayout(LayoutKind.Sequential)] - private struct MSLLHOOKSTRUCT - { - public POINT pt; - public uint mouseData; - public uint flags; - public uint time; - public IntPtr dwExtraInfo; - } - - private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam); - - // Mouse hook management - private IntPtr mouseHookHandle = IntPtr.Zero; - private LowLevelMouseProc? mouseHookCallback; - - private Rect? frameOuterRect; - private Rect? frameInnerRect; - private readonly Ellipse? hoverCursorRing; - // Added fields for hole effect - private Geometry? baseFrameGeometry; // original frame geometry (outer minus inner) - private double pathOffsetX; // offset of geometry within window - private double pathOffsetY; - private readonly HoleCache primaryHoleCache = new(); - - private static readonly MediaColor CoolColor = MediaColor.FromRgb(220, 235, 255); - private static readonly MediaColor WarmColor = MediaColor.FromRgb(255, 220, 180); - - private const uint MOD_CONTROL = 0x0002; - private const uint MOD_SHIFT = 0x0004; - private const uint VK_L = 0x4C; - private const uint VK_UP = 0x26; - private const uint VK_DOWN = 0x28; - - public MainWindow() - { - InitializeComponent(); - hoverCursorRing = FindName("HoverCursorRing") as Ellipse; - - // Load settings - settings = AppSettings.Load(); - - // Restore persisted state - isLightOn = settings.IsLightOn; - currentOpacity = Math.Max(MinOpacity, Math.Min(MaxOpacity, settings.Brightness)); - _colorTemperature = Math.Max(MinColorTemp, Math.Min(MaxColorTemp, settings.ColorTemperature)); - - // Save back if values were clamped - if (currentOpacity != settings.Brightness || _colorTemperature != settings.ColorTemperature) - { - settings.Brightness = currentOpacity; - settings.ColorTemperature = _colorTemperature; - settings.Save(); - } - - SetupNotifyIcon(); - } - - private void SetupNotifyIcon() - { - notifyIcon = new NotifyIcon(); - - // Load icon from embedded resource or file - try - { - var iconPath = System.IO.Path.Combine(AppContext.BaseDirectory, "ringlight_cropped.ico"); - if (File.Exists(iconPath)) - { - notifyIcon.Icon = new System.Drawing.Icon(iconPath); - } - else - { - // Try application icon from exe - var appIcon = System.Drawing.Icon.ExtractAssociatedIcon(Environment.ProcessPath ?? System.Reflection.Assembly.GetExecutingAssembly().Location); - notifyIcon.Icon = appIcon ?? System.Drawing.SystemIcons.Application; - } - } - catch (Exception) - { - // Fallback to default icon if loading fails - notifyIcon.Icon = System.Drawing.SystemIcons.Application; - } - - notifyIcon.Text = "Windows Edge Light - Right-click for options"; - notifyIcon.Visible = true; - - var contextMenu = new ContextMenuStrip(); - contextMenu.Items.Add("📋 Keyboard Shortcuts", null, (s, e) => ShowHelp()); - contextMenu.Items.Add(new ToolStripSeparator()); - contextMenu.Items.Add("💡 Toggle Light (Ctrl+Shift+L)", null, (s, e) => ToggleLight()); - contextMenu.Items.Add("🔆 Brightness Up (Ctrl+Shift+↑)", null, (s, e) => IncreaseBrightness()); - contextMenu.Items.Add("🔅 Brightness Down (Ctrl+Shift+↓)", null, (s, e) => DecreaseBrightness()); - contextMenu.Items.Add(new ToolStripSeparator()); - contextMenu.Items.Add("🔥 K- Warmer Light", null, (s, e) => IncreaseColorTemperature()); - contextMenu.Items.Add("❄️ K+ Cooler Light", null, (s, e) => DecreaseColorTemperature()); - contextMenu.Items.Add(new ToolStripSeparator()); - contextMenu.Items.Add("🖥️ Switch Monitor", null, (s, e) => MoveToNextMonitor()); - contextMenu.Items.Add("🖥️🖥️ Toggle All Monitors", null, (s, e) => ToggleAllMonitors()); - contextMenu.Items.Add(new ToolStripSeparator()); - - // Add toggle controls menu item - text will be set by UpdateTrayMenuToggleControlsText - toggleControlsMenuItem = new ToolStripMenuItem("🎛️ Hide Controls", null, (s, e) => ToggleControlsVisibility()); - contextMenu.Items.Add(toggleControlsMenuItem); - contextMenu.Items.Add("📍 Reset Control Bar Position", null, (s, e) => ResetControlWindowPosition()); - - // Add exclude from capture menu item with checkmark - excludeFromCaptureMenuItem = new ToolStripMenuItem("🎥 Exclude from Screen Capture", null, (s, e) => ToggleExcludeFromCapture()); - excludeFromCaptureMenuItem.CheckOnClick = true; - excludeFromCaptureMenuItem.Checked = settings.ExcludeFromCapture; - contextMenu.Items.Add(excludeFromCaptureMenuItem); - - contextMenu.Items.Add(new ToolStripSeparator()); - contextMenu.Items.Add("✖ Exit", null, (s, e) => System.Windows.Application.Current.Shutdown()); - - notifyIcon.ContextMenuStrip = contextMenu; - notifyIcon.DoubleClick += (s, e) => ShowHelp(); - - // Set initial menu text based on current state - UpdateTrayMenuToggleControlsText(); - } - - private void ShowHelp() - { - var version = System.Reflection.Assembly.GetExecutingAssembly() - .GetName().Version?.ToString() ?? "Unknown"; - - var helpMessage = $@"Windows Edge Light - Keyboard Shortcuts - -💡 Toggle Light: Ctrl + Shift + L -🔆 Brightness Up: Ctrl + Shift + ↑ -🔅 Brightness Down: Ctrl + Shift + ↓ - -💡 Features: -• Click-through overlay - won't interfere with your work -• Global hotkeys work from any application -• Right-click taskbar icon for full menu -• Control toolbar with brightness, color temp, and monitor options -• Color temperature controls (🔥 warmer, ❄️ cooler) -• Switch between monitors or show on all monitors -• Exclude from screen capture (🎥) - invisible in Teams/Zoom sharing - -Created by Scott Hanselman -Version {version}"; - - System.Windows.MessageBox.Show(helpMessage, "Windows Edge Light - Help", - MessageBoxButton.OK, MessageBoxImage.Information); - } - - private void SetupWindow() - { - // Initialize available monitors on first setup - if (availableMonitors.Length == 0) - { - RefreshAvailableMonitors(); - - // Find the primary monitor index - for (int i = 0; i < availableMonitors.Length; i++) - { - if (availableMonitors[i].Primary) - { - currentMonitorIndex = i; - break; - } - } - } - - var targetScreen = GetCurrentScreen(); - if (targetScreen == null) return; - - SetupWindowForScreen(targetScreen); - } - - private void SetupWindowForScreen(Screen screen) - { - // Use WorkingArea instead of Bounds to exclude taskbar - var workingArea = screen.WorkingArea; - - // Get DPI scale factor for the target screen - (_dpiScaleX, _dpiScaleY) = GetDpiForScreen(screen); - - // Convert physical pixels to WPF DIPs - this.Left = workingArea.X / _dpiScaleX; - this.Top = workingArea.Y / _dpiScaleY; - this.Width = workingArea.Width / _dpiScaleX; - this.Height = workingArea.Height / _dpiScaleY; - this.WindowState = System.Windows.WindowState.Normal; - } - - private void Window_Loaded(object sender, RoutedEventArgs e) - { - SetupWindow(); - CreateFrameGeometry(); - CreateControlWindow(); - - var hwnd = new WindowInteropHelper(this).Handle; - int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); - SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT | WS_EX_LAYERED); - - RegisterGlobalHotKeys(hwnd); - - // Hook into Windows message processing - HwndSource source = HwndSource.FromHwnd(hwnd); - source.AddHook(HwndHook); - - // Listen for window size/location changes (docking/undocking) - this.SizeChanged += Window_SizeChanged; - this.LocationChanged += Window_LocationChanged; - - // Apply exclude from capture setting - ApplyExcludeFromCapture(); - - // Apply persisted brightness and color temperature - EdgeLightBorder.Opacity = currentOpacity; - SetColorTemperature(_colorTemperature); - - // Apply persisted on/off state - if (!isLightOn) - { - EdgeLightBorder.Visibility = Visibility.Collapsed; - } - - InstallMouseHook(); - } - - private void RegisterGlobalHotKeys(IntPtr hwnd) - { - var failedHotKeys = new List(); - - if (!RegisterHotKey(hwnd, HOTKEY_TOGGLE, MOD_CONTROL | MOD_SHIFT, VK_L)) - { - failedHotKeys.Add("Toggle Light (Ctrl+Shift+L)"); - } - - if (!RegisterHotKey(hwnd, HOTKEY_BRIGHTNESS_UP, MOD_CONTROL | MOD_SHIFT, VK_UP)) - { - failedHotKeys.Add("Brightness Up (Ctrl+Shift+Up)"); - } - - if (!RegisterHotKey(hwnd, HOTKEY_BRIGHTNESS_DOWN, MOD_CONTROL | MOD_SHIFT, VK_DOWN)) - { - failedHotKeys.Add("Brightness Down (Ctrl+Shift+Down)"); - } - - if (failedHotKeys.Count > 0) - { - notifyIcon?.ShowBalloonTip( - 5000, - "Windows Edge Light hotkey conflict", - "Some keyboard shortcuts could not be registered because another app is using them:\n\n" + - string.Join("\n", failedHotKeys) + - "\n\nUse the tray menu controls instead.", - ToolTipIcon.Warning); - } - } - - private void InstallMouseHook() - { - // Store callback to prevent garbage collection - mouseHookCallback = MouseHookProc; - - using var curProcess = System.Diagnostics.Process.GetCurrentProcess(); - using var curModule = curProcess.MainModule; - if (curModule != null) - { - mouseHookHandle = SetWindowsHookEx(WH_MOUSE_LL, mouseHookCallback, - GetModuleHandle(curModule.ModuleName), 0); - } - } - - private void UninstallMouseHook() - { - if (mouseHookHandle != IntPtr.Zero) - { - UnhookWindowsHookEx(mouseHookHandle); - mouseHookHandle = IntPtr.Zero; - } - } - - private IntPtr MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) - { - if (nCode >= 0 && wParam == (IntPtr)WM_MOUSEMOVE) - { - var hookStruct = Marshal.PtrToStructure(lParam); - - // Dispatch to UI thread for WPF operations - Dispatcher.BeginInvoke(new Action(() => - { - HandleMouseMove(hookStruct.pt.x, hookStruct.pt.y); - }), System.Windows.Threading.DispatcherPriority.Input); - } - - return CallNextHookEx(mouseHookHandle, nCode, wParam, lParam); - } - - private void HandleMouseMove(int screenX, int screenY) - { - if (!isLightOn) - { - if (EdgeLightBorder.Visibility != Visibility.Collapsed) - { - EdgeLightBorder.Visibility = Visibility.Collapsed; - } - - if (hoverCursorRing != null && hoverCursorRing.Visibility != Visibility.Collapsed) - { - hoverCursorRing.Visibility = Visibility.Collapsed; - } - // Restore original geometry if previously punched - if (baseFrameGeometry != null && EdgeLightBorder.Data != baseFrameGeometry) - { - EdgeLightBorder.Data = baseFrameGeometry; - } - - // Also handle additional windows - foreach (var ctx in additionalMonitorWindows) - { - if (ctx.BorderPath.Visibility != Visibility.Collapsed) - ctx.BorderPath.Visibility = Visibility.Collapsed; - if (ctx.HoverRing.Visibility != Visibility.Collapsed) - ctx.HoverRing.Visibility = Visibility.Collapsed; - if (ctx.BorderPath.Data != ctx.BaseGeometry) - ctx.BorderPath.Data = ctx.BaseGeometry; - } - - return; - } - - // --- Main Window Logic --- - if (frameOuterRect != null && frameInnerRect != null && hoverCursorRing != null && baseFrameGeometry != null) - { - var screen = GetCurrentScreen(); - if (screen != null) - { - ApplyHolePunchEffect( - screenX, screenY, - screen, - _dpiScaleX, _dpiScaleY, - frameOuterRect.Value, frameInnerRect.Value, - hoverCursorRing, - EdgeLightBorder, - baseFrameGeometry, - pathOffsetX, pathOffsetY, - (ring, x, y) => { Canvas.SetLeft(ring, x); Canvas.SetTop(ring, y); }, - primaryHoleCache - ); - } - } - - // --- Additional Windows Logic --- - foreach (var ctx in additionalMonitorWindows) - { - try - { - ApplyHolePunchEffect( - screenX, screenY, - ctx.Screen, - ctx.DpiScaleX, ctx.DpiScaleY, - ctx.FrameOuterRect, ctx.FrameInnerRect, - ctx.HoverRing, - ctx.BorderPath, - ctx.BaseGeometry, - ctx.PathOffsetX, ctx.PathOffsetY, - (ring, x, y) => { ring.Margin = new Thickness(x, y, 0, 0); }, - ctx.HoleCache - ); - } - catch (InvalidOperationException) - { - // Can happen if window is closing or not ready - } - } - } - - private void ApplyHolePunchEffect( - int screenX, int screenY, - Screen screen, - double dpiScaleX, double dpiScaleY, - Rect frameOuterRect, Rect frameInnerRect, - Ellipse hoverRing, - System.Windows.Shapes.Path borderPath, - Geometry baseGeometry, - double pathOffsetX, double pathOffsetY, - Action positionRing, - HoleCache holeCache) - { - // Manual coordinate calculation to avoid PointFromScreen issues across monitors/DPIs - // We positioned the window using dpiScaleX/Y relative to the screen WorkingArea. - double relX = (screenX - screen.WorkingArea.X) / dpiScaleX; - double relY = (screenY - screen.WorkingArea.Y) / dpiScaleY; - var windowPt = new System.Windows.Point(relX, relY); - - // Existing frame band detection (outer minus inner) - bool inFrameBand = frameOuterRect.Contains(windowPt) && !frameInnerRect.Contains(windowPt); - - // Early detection zone just inside the inner edge: a band with thickness = hole radius (cursor ring radius) - double ringDiameter = hoverRing.Width; - double holeRadius = ringDiameter / 2; // match ring size - var innerProximityRect = new Rect( - frameInnerRect.X + holeRadius, - frameInnerRect.Y + holeRadius, - frameInnerRect.Width - (holeRadius * 2), - frameInnerRect.Height - (holeRadius * 2)); - - // Near from inside means inside innerRect but within holeRadius of its edge (i.e., not deep inside innerProximityRect) - bool nearFromInside = frameInnerRect.Contains(windowPt) && !innerProximityRect.Contains(windowPt); - - bool overFrame = inFrameBand || nearFromInside; - - if (overFrame) - { - positionRing(hoverRing, windowPt.X - ringDiameter / 2, windowPt.Y - ringDiameter / 2); - - if (hoverRing.Visibility != Visibility.Visible) - { - hoverRing.Visibility = Visibility.Visible; - } - - // Punch a transparent hole under the ring by excluding a circle geometry from the frame - // Convert window coordinates to geometry local coordinates by subtracting stored offsets - var localCenter = new System.Windows.Point(windowPt.X - pathOffsetX, windowPt.Y - pathOffsetY); - if (holeCache.BaseGeometry != baseGeometry || - holeCache.Hole == null || - holeCache.Hole.RadiusX != holeRadius || - holeCache.Combined == null) - { - holeCache.BaseGeometry = baseGeometry; - holeCache.Hole = new EllipseGeometry(localCenter, holeRadius, holeRadius); - holeCache.Combined = new CombinedGeometry(GeometryCombineMode.Exclude, baseGeometry, holeCache.Hole); - } - else - { - holeCache.Hole.Center = localCenter; - } - - borderPath.Data = holeCache.Combined; - } - else - { - if (hoverRing.Visibility != Visibility.Collapsed) - { - hoverRing.Visibility = Visibility.Collapsed; - } - - if (borderPath.Visibility != Visibility.Visible) - { - borderPath.Visibility = Visibility.Visible; - } - // Restore original geometry (remove hole) - if (baseGeometry != null && borderPath.Data != baseGeometry) - { - borderPath.Data = baseGeometry; - } - } - } - - private void CreateControlWindow() - { - controlWindow = new ControlWindow(this); - RepositionControlWindow(); - - // Only show if controls are supposed to be visible - if (isControlWindowVisible) - { - controlWindow.Show(); - } - } - - private void CreateFrameGeometry() - { - // Get actual dimensions (accounting for margin) - double width = this.ActualWidth - 40; // 20px margin on each side - double height = this.ActualHeight - 40; - - const double frameThickness = 80; - const double outerRadius = 100; // Extra rounded like macOS - const double innerRadius = 60; // Keep proportional - - // Outer rounded rectangle - var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); - - // Inner rounded rectangle - var innerRect = new RectangleGeometry( - new Rect(frameThickness, frameThickness, - width - (frameThickness * 2), - height - (frameThickness * 2)), - innerRadius, innerRadius); - - // Combine: outer minus inner = frame - var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); - baseFrameGeometry = frameGeometry; // store original - EdgeLightBorder.Data = frameGeometry; - pathOffsetX = (ActualWidth - width) / 2.0; // store offsets for local coordinate conversion - pathOffsetY = (ActualHeight - height) / 2.0; - // Expand outer and contract inner rects for earlier hover detection based on ring hole radius. - double ringDiameter = hoverCursorRing?.Width ?? 0; - double holeRadius = ringDiameter / 2.0; - frameOuterRect = new Rect(pathOffsetX - holeRadius, pathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); - frameInnerRect = new Rect(pathOffsetX + frameThickness + holeRadius, pathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); - } - - private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) - { - const int WM_HOTKEY = 0x0312; - - if (msg == WM_HOTKEY) - { - int hotkeyId = wParam.ToInt32(); - - switch (hotkeyId) - { - case HOTKEY_TOGGLE: - ToggleLight(); - handled = true; - break; - case HOTKEY_BRIGHTNESS_UP: - IncreaseBrightness(); - handled = true; - break; - case HOTKEY_BRIGHTNESS_DOWN: - DecreaseBrightness(); - handled = true; - break; - } - } - - return IntPtr.Zero; - } - - protected override void OnDpiChanged(DpiScale oldDpi, DpiScale newDpi) - { - base.OnDpiChanged(oldDpi, newDpi); - - _dpiScaleX = newDpi.DpiScaleX; - _dpiScaleY = newDpi.DpiScaleY; - - // Ensure window covers the current monitor correctly with new DPI - if (availableMonitors.Length > 0) - { - // Re-verify which monitor we are on, as we might have just moved - UpdateCurrentMonitorIndex(); - - if (currentMonitorIndex < availableMonitors.Length) - { - var screen = availableMonitors[currentMonitorIndex]; - var workingArea = screen.WorkingArea; - - // Only update if significantly different to avoid loops - double newLeft = workingArea.X / _dpiScaleX; - double newTop = workingArea.Y / _dpiScaleY; - double newWidth = workingArea.Width / _dpiScaleX; - double newHeight = workingArea.Height / _dpiScaleY; - - if (Math.Abs(this.Left - newLeft) > 1 || Math.Abs(this.Top - newTop) > 1 || - Math.Abs(this.Width - newWidth) > 1 || Math.Abs(this.Height - newHeight) > 1) - { - this.Left = newLeft; - this.Top = newTop; - this.Width = newWidth; - this.Height = newHeight; - } - } - } - } - - protected override void OnClosed(EventArgs e) - { - UninstallMouseHook(); - - var hwnd = new WindowInteropHelper(this).Handle; - UnregisterHotKey(hwnd, HOTKEY_TOGGLE); - UnregisterHotKey(hwnd, HOTKEY_BRIGHTNESS_UP); - UnregisterHotKey(hwnd, HOTKEY_BRIGHTNESS_DOWN); - - if (notifyIcon != null) - { - notifyIcon.Visible = false; - notifyIcon.Dispose(); - } - - HideAdditionalMonitorWindows(); - controlWindow?.Close(); - - base.OnClosed(e); - } - - private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) - { - if (e.Key == Key.L && - (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && - (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) - { - ToggleLight(); - } - else if (e.Key == Key.Escape) - { - System.Windows.Application.Current.Shutdown(); - } - } - - private void Toggle_Click(object sender, RoutedEventArgs e) - { - ToggleLight(); - } - - private void ToggleLight() - { - isLightOn = !isLightOn; - if (isLightOn) - { - EdgeLightBorder.Visibility = Visibility.Visible; - // Restore base geometry on toggle if needed - if (baseFrameGeometry != null) - { - EdgeLightBorder.Data = baseFrameGeometry; - } - } - else - { - EdgeLightBorder.Visibility = Visibility.Collapsed; - if (hoverCursorRing != null) - { - hoverCursorRing.Visibility = Visibility.Collapsed; - } - } - - // Update all additional monitor windows - UpdateAdditionalMonitorWindows(); - - settings.IsLightOn = isLightOn; - settings.Save(); - } - - public void HandleToggle() - { - ToggleLight(); - } - - public void ToggleControlsVisibility() - { - isControlWindowVisible = !isControlWindowVisible; - - // Apply visibility change if control window exists - if (controlWindow != null) - { - if (isControlWindowVisible) - { - controlWindow.Show(); - } - else - { - controlWindow.Hide(); - } - } - // Note: If controlWindow doesn't exist yet, isControlWindowVisible state - // is preserved and will be applied when CreateControlWindow() is called - - UpdateTrayMenuToggleControlsText(); - } - - private void UpdateTrayMenuToggleControlsText() - { - if (toggleControlsMenuItem != null) - { - toggleControlsMenuItem.Text = isControlWindowVisible ? "🎛️ Hide Controls" : "🎛️ Show Controls"; - } - } - - public void ToggleExcludeFromCapture() - { - settings.ExcludeFromCapture = !settings.ExcludeFromCapture; - settings.Save(); - - // Update menu checkmark - if (excludeFromCaptureMenuItem != null) - { - excludeFromCaptureMenuItem.Checked = settings.ExcludeFromCapture; - } - - // Apply the setting to all windows - ApplyExcludeFromCapture(); - } - - private void ApplyExcludeFromCapture() - { - var hwnd = new WindowInteropHelper(this).Handle; - if (hwnd != IntPtr.Zero) - { - var result = SetWindowDisplayAffinity(hwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); - if (!result) - { - var error = Marshal.GetLastWin32Error(); - System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for main window. Error: {error}"); - } - } - - // Apply to control window - if (controlWindow != null) - { - var controlHwnd = new WindowInteropHelper(controlWindow).Handle; - if (controlHwnd != IntPtr.Zero) - { - var result = SetWindowDisplayAffinity(controlHwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); - if (!result) - { - var error = Marshal.GetLastWin32Error(); - System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for control window. Error: {error}"); - } - } - } - - // Apply to all additional monitor windows - foreach (var ctx in additionalMonitorWindows) - { - var monitorHwnd = new WindowInteropHelper(ctx.Window).Handle; - if (monitorHwnd != IntPtr.Zero) - { - var result = SetWindowDisplayAffinity(monitorHwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); - if (!result) - { - var error = Marshal.GetLastWin32Error(); - System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for monitor window. Error: {error}"); - } - } - } - } - - public void IncreaseBrightness() - { - SetBrightness(currentOpacity + OpacityStep); - } - - public void DecreaseBrightness() - { - SetBrightness(currentOpacity - OpacityStep); - } - - public void SetBrightness(double value, bool save = true) - { - currentOpacity = Math.Max(MinOpacity, Math.Min(MaxOpacity, value)); - EdgeLightBorder.Opacity = currentOpacity; - UpdateAdditionalMonitorWindows(); - - if (save) - { - settings.Brightness = currentOpacity; - settings.Save(); - } - } - - private void UpdateAdditionalMonitorWindows() - { - foreach (var ctx in additionalMonitorWindows) - { - var path = ctx.BorderPath; - path.Opacity = currentOpacity; - path.Visibility = isLightOn ? Visibility.Visible : Visibility.Collapsed; - ApplyColorTemperature(path); - } - } - - public void IncreaseColorTemperature() - { - SetColorTemperature(_colorTemperature + ColorTempStep); - } - - public void DecreaseColorTemperature() - { - SetColorTemperature(_colorTemperature - ColorTempStep); - } - - public void SetColorTemperature(double value, bool save = true) - { - _colorTemperature = Math.Max(MinColorTemp, Math.Min(MaxColorTemp, value)); - ApplyColorTemperature(EdgeLightBorder); - - // Update all additional monitor windows - UpdateAdditionalMonitorWindows(); - - if (save) - { - settings.ColorTemperature = _colorTemperature; - settings.Save(); - } - } - - public void MoveToNextMonitor() - { - // If in all monitors mode, do nothing - if (showOnAllMonitors) return; - - // Refresh monitor list in case of hot-plug/unplug - RefreshAvailableMonitors(); - - if (availableMonitors.Length <= 1) - { - return; - } - - // Ensure currentMonitorIndex is accurate before moving - UpdateCurrentMonitorIndex(); - - _isManualMonitorSwitch = true; - try - { - // Cycle to next monitor - currentMonitorIndex = (currentMonitorIndex + 1) % availableMonitors.Length; - var targetScreen = availableMonitors[currentMonitorIndex]; - - // Reposition main window to new monitor using physical coordinates to trigger DPI change correctly - var hwnd = new WindowInteropHelper(this).Handle; - SetWindowPos(hwnd, IntPtr.Zero, - targetScreen.WorkingArea.X, targetScreen.WorkingArea.Y, - targetScreen.WorkingArea.Width, targetScreen.WorkingArea.Height, - SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); - - // Force a size update if DPI didn't change (SetWindowPos might not trigger OnDpiChanged) - // If DPI changed, OnDpiChanged will handle it. - // But we can't easily know if OnDpiChanged fired yet. - // However, setting properties to the same value is cheap in WPF. - // We need to ensure we use the NEW DPI if it changed. - // OnDpiChanged updates _dpiScaleX/Y. - - // If we are on the same thread, OnDpiChanged (via WM_DPICHANGED) should have fired synchronously during SetWindowPos. - // So _dpiScaleX/Y should be up to date. - - double newLeft = targetScreen.WorkingArea.X / _dpiScaleX; - double newTop = targetScreen.WorkingArea.Y / _dpiScaleY; - double newWidth = targetScreen.WorkingArea.Width / _dpiScaleX; - double newHeight = targetScreen.WorkingArea.Height / _dpiScaleY; - - this.Left = newLeft; - this.Top = newTop; - this.Width = newWidth; - this.Height = newHeight; - } - finally - { - _isManualMonitorSwitch = false; - } - - // An explicit monitor switch should bring the controls to the selected monitor. - ResetControlWindowPosition(); - } - - [DllImport("user32.dll", SetLastError = true)] - private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); - private const uint SWP_NOZORDER = 0x0004; - private const uint SWP_NOACTIVATE = 0x0010; - private const uint SWP_FRAMECHANGED = 0x0020; - - public void ToggleAllMonitors() - { - showOnAllMonitors = !showOnAllMonitors; - - if (showOnAllMonitors) - { - ShowOnAllMonitors(); - } - else - { - HideAdditionalMonitorWindows(); - } - - controlWindow?.UpdateAllMonitorsButtonState(); - } - - private void ShowOnAllMonitors() - { - RefreshAvailableMonitors(); - - // Close any existing additional windows - HideAdditionalMonitorWindows(); - - // Create a window for each monitor except the current one (this window) - for (int i = 0; i < availableMonitors.Length; i++) - { - if (i != currentMonitorIndex) - { - var monitorCtx = CreateMonitorWindow(availableMonitors[i]); - additionalMonitorWindows.Add(monitorCtx); - monitorCtx.Window.Show(); - } - } - } - - private void HideAdditionalMonitorWindows() - { - foreach (var ctx in additionalMonitorWindows) - { - ctx.Window.Close(); - } - additionalMonitorWindows.Clear(); - } - - private MonitorWindowContext CreateMonitorWindow(Screen screen) - { - var window = new Window - { - Title = "Windows Edge Light", - AllowsTransparency = true, - Background = System.Windows.Media.Brushes.Transparent, - ResizeMode = ResizeMode.NoResize, - ShowInTaskbar = false, - Topmost = true, - WindowStyle = WindowStyle.None - }; - - // Position on the target screen - var workingArea = screen.WorkingArea; - - // Get the correct DPI scale for THIS specific screen - var (screenDpiX, screenDpiY) = GetDpiForScreen(screen); - - // Convert physical pixels to WPF DIPs using the correct per-monitor DPI - window.Left = workingArea.X / screenDpiX; - window.Top = workingArea.Y / screenDpiY; - window.Width = workingArea.Width / screenDpiX; - window.Height = workingArea.Height / screenDpiY; - - // Create the grid and edge light border - var grid = new System.Windows.Controls.Grid { IsHitTestVisible = false }; - var path = new System.Windows.Shapes.Path - { - HorizontalAlignment = System.Windows.HorizontalAlignment.Center, - VerticalAlignment = System.Windows.VerticalAlignment.Center, - Stretch = System.Windows.Media.Stretch.None, - Opacity = currentOpacity, - Visibility = isLightOn ? Visibility.Visible : Visibility.Collapsed - }; - - var temperatureColor = GetColorForTemperature(_colorTemperature); - var gradient = new LinearGradientBrush - { - StartPoint = new System.Windows.Point(0, 0), - EndPoint = new System.Windows.Point(1, 1) - }; - gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 0.0)); - gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.3)); - gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.5)); - gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.7)); - gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 1.0)); - path.Fill = gradient; - - // Add drop shadow effect - path.Effect = new DropShadowEffect - { - BlurRadius = 76, - Opacity = 1, - ShadowDepth = 0, - Color = temperatureColor - }; - - // Create hover ring (Ellipse) - var hoverRing = new Ellipse - { - Width = 140, - Height = 140, - Fill = System.Windows.Media.Brushes.Transparent, - Visibility = Visibility.Collapsed, - HorizontalAlignment = System.Windows.HorizontalAlignment.Left, - VerticalAlignment = System.Windows.VerticalAlignment.Top - }; - // Add drop shadow to ring - actually main window doesn't seem to have this on the ring itself? - // Main window XAML doesn't show effect on HoverCursorRing. - // So removing effect to match. - - // Create frame geometry - double width = window.Width - 40; - double height = window.Height - 40; - const double frameThickness = 80; - const double outerRadius = 100; - const double innerRadius = 60; - - var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); - var innerRect = new RectangleGeometry( - new Rect(frameThickness, frameThickness, - width - (frameThickness * 2), - height - (frameThickness * 2)), - innerRadius, innerRadius); - - var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); - path.Data = frameGeometry; - - grid.Children.Add(path); - grid.Children.Add(hoverRing); - window.Content = grid; - - // Calculate geometry data for hole punch - double pathOffsetX = (window.Width - width) / 2.0; - double pathOffsetY = (window.Height - height) / 2.0; - - double ringDiameter = hoverRing.Width; - double holeRadius = ringDiameter / 2.0; - var frameOuterRect = new Rect(pathOffsetX - holeRadius, pathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); - var frameInnerRect = new Rect(pathOffsetX + frameThickness + holeRadius, pathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); - - var ctx = new MonitorWindowContext - { - Window = window, - Screen = screen, - BorderPath = path, - HoverRing = hoverRing, - BaseGeometry = frameGeometry, - FrameOuterRect = frameOuterRect, - FrameInnerRect = frameInnerRect, - PathOffsetX = pathOffsetX, - PathOffsetY = pathOffsetY, - DpiScaleX = screenDpiX, // Use calculated DPI for this screen - DpiScaleY = screenDpiY - }; - - // Make window click-through and handle DPI - window.Loaded += (s, e) => - { - var hwnd = new WindowInteropHelper(window).Handle; - int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); - SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT | WS_EX_LAYERED); - - // Apply exclude from capture setting - var result = SetWindowDisplayAffinity(hwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); - if (!result) - { - var error = Marshal.GetLastWin32Error(); - System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for monitor window during creation. Error: {error}"); - } - - // Verify and update DPI if WPF reports a different value after window is loaded - var source = PresentationSource.FromVisual(window); - if (source != null) - { - double dpiX = source.CompositionTarget.TransformToDevice.M11; - double dpiY = source.CompositionTarget.TransformToDevice.M22; - - // Only reposition if DPI changed significantly from our initial calculation - if (Math.Abs(dpiX - ctx.DpiScaleX) > 0.01 || Math.Abs(dpiY - ctx.DpiScaleY) > 0.01) - { - ctx.DpiScaleX = dpiX; - ctx.DpiScaleY = dpiY; - - // Reposition/Resize with correct DPI - window.Left = screen.WorkingArea.X / dpiX; - window.Top = screen.WorkingArea.Y / dpiY; - window.Width = screen.WorkingArea.Width / dpiX; - window.Height = screen.WorkingArea.Height / dpiY; - - // Recalculate geometry for new window size - UpdateMonitorGeometry(ctx); - } - } - }; - - window.DpiChanged += (s, dpiArgs) => - { - ctx.DpiScaleX = dpiArgs.NewDpi.DpiScaleX; - ctx.DpiScaleY = dpiArgs.NewDpi.DpiScaleY; - - window.Left = screen.WorkingArea.X / ctx.DpiScaleX; - window.Top = screen.WorkingArea.Y / ctx.DpiScaleY; - window.Width = screen.WorkingArea.Width / ctx.DpiScaleX; - window.Height = screen.WorkingArea.Height / ctx.DpiScaleY; - - UpdateMonitorGeometry(ctx); - }; - - return ctx; - } - - private void UpdateMonitorGeometry(MonitorWindowContext ctx) - { - double width = ctx.Window.Width - 40; - double height = ctx.Window.Height - 40; - const double frameThickness = 80; - const double outerRadius = 100; - const double innerRadius = 60; - - var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); - var innerRect = new RectangleGeometry( - new Rect(frameThickness, frameThickness, - width - (frameThickness * 2), - height - (frameThickness * 2)), - innerRadius, innerRadius); - - var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); - - ctx.BaseGeometry = frameGeometry; - ctx.BorderPath.Data = frameGeometry; - - ctx.PathOffsetX = (ctx.Window.Width - width) / 2.0; - ctx.PathOffsetY = (ctx.Window.Height - height) / 2.0; - - double ringDiameter = ctx.HoverRing.Width; - double holeRadius = ringDiameter / 2.0; - - ctx.FrameOuterRect = new Rect(ctx.PathOffsetX - holeRadius, ctx.PathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); - ctx.FrameInnerRect = new Rect(ctx.PathOffsetX + frameThickness + holeRadius, ctx.PathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); - } - - public bool IsShowingOnAllMonitors() - { - return showOnAllMonitors; - } - - private void RepositionControlWindow() - { - if (controlWindow == null) return; - - // Respect a user-dragged position for the current session. - if (controlWindowManuallyMoved) return; - - // Position at bottom center of main window - controlWindow.Left = this.Left + (this.Width - controlWindow.Width) / 2; - controlWindow.Top = this.Top + this.Height - controlWindow.Height - 124; - } - - public void NotifyControlWindowManuallyMoved() - { - controlWindowManuallyMoved = true; - } - - public void ResetControlWindowPosition() - { - controlWindowManuallyMoved = false; - RepositionControlWindow(); - } - - public bool HasMultipleMonitors() - { - // Refresh monitor count to handle hot-plug scenarios - RefreshAvailableMonitors(); - return availableMonitors.Length > 1; - } - - public bool IsExcludeFromCaptureEnabled() - { - return settings.ExcludeFromCapture; - } - - public double GetBrightness() => currentOpacity; - - public double GetColorTemperature() => _colorTemperature; - - public void SaveAppearanceSettings() - { - settings.Brightness = currentOpacity; - settings.ColorTemperature = _colorTemperature; - settings.Save(); - } - - public bool GetIsToggleButtonVisible() => settings.ShowToggleButton; - - public bool GetIsBrightnessButtonsVisible() => settings.ShowBrightnessButtons; - - public bool GetIsColorTempButtonsVisible() => settings.ShowColorTempButtons; - - public bool GetIsControlMonitorsButtonVisible() => settings.ShowMonitorControlButtons; - - public void SetIsToggleVisible(bool isVisible) - { - settings.ShowToggleButton = isVisible; - settings.Save(); - } - - public void SetIsBrightnessButtonsVisible(bool isVisible) - { - settings.ShowBrightnessButtons = isVisible; - settings.Save(); - } - - public void SetIsColorTempButtonsVisible(bool isVisible) - { - settings.ShowColorTempButtons = isVisible; - settings.Save(); - } - - public void SetIsControlMonitorsButtonVisible(bool isVisible) - { - settings.ShowMonitorControlButtons = isVisible; - settings.Save(); - } - - private void Window_SizeChanged(object sender, SizeChangedEventArgs e) - { - // Recreate geometry when window size changes (e.g., different monitor resolution) - if (EdgeLightBorder != null) - { - CreateFrameGeometry(); - } - - // Reposition control window - RepositionControlWindow(); - - // Update which monitor we're actually on - UpdateCurrentMonitorIndex(); - } - - private void Window_LocationChanged(object? sender, EventArgs e) - { - // Reposition control window when main window moves - RepositionControlWindow(); - - // Update which monitor we're actually on - UpdateCurrentMonitorIndex(); - } - - private void UpdateCurrentMonitorIndex() - { - // If we are manually switching, trust the index we set explicitly - if (_isManualMonitorSwitch) return; - - RefreshAvailableMonitors(); - - if (availableMonitors.Length == 0) return; - - try - { - // Use PointToScreen to get accurate physical coordinates of the window center - // This handles DPI scaling correctly unlike manual calculation - var centerPoint = this.PointToScreen(new System.Windows.Point(this.ActualWidth / 2, this.ActualHeight / 2)); - var drawingPoint = new System.Drawing.Point((int)centerPoint.X, (int)centerPoint.Y); - - for (int i = 0; i < availableMonitors.Length; i++) - { - if (availableMonitors[i].Bounds.Contains(drawingPoint)) - { - currentMonitorIndex = i; - break; - } - } - } - catch (InvalidOperationException) - { - // Window might not be loaded or visible yet - } - } - - private void RefreshAvailableMonitors() - { - availableMonitors = Screen.AllScreens; - currentMonitorIndex = availableMonitors.Length == 0 - ? 0 - : Math.Clamp(currentMonitorIndex, 0, availableMonitors.Length - 1); - } - - private Screen? GetCurrentScreen() - { - if (availableMonitors.Length == 0) - { - return Screen.PrimaryScreen; - } - - currentMonitorIndex = Math.Clamp(currentMonitorIndex, 0, availableMonitors.Length - 1); - return availableMonitors[currentMonitorIndex]; - } - - private static MediaColor GetColorForTemperature(double temperature) - { - byte Lerp(byte cool, byte warm) => (byte)(cool + ((warm - cool) * temperature)); - return MediaColor.FromRgb( - Lerp(CoolColor.R, WarmColor.R), - Lerp(CoolColor.G, WarmColor.G), - Lerp(CoolColor.B, WarmColor.B)); - } - - private void ApplyColorTemperature(System.Windows.Shapes.Path path) - { - var temperatureColor = GetColorForTemperature(_colorTemperature); - - if (path.Fill is LinearGradientBrush brush) - { - foreach (var stop in brush.GradientStops) - { - if (stop.Offset is > 0.2 and < 0.8) - { - stop.Color = temperatureColor; - } - } - } - - if (path.Effect is DropShadowEffect shadow) - { - shadow.Color = temperatureColor; - } - } - - private (double dpiScaleX, double dpiScaleY) GetDpiForScreen(Screen screen) - { - try - { - // Get monitor handle for the center of the screen - var centerPoint = new POINT - { - x = screen.Bounds.X + screen.Bounds.Width / 2, - y = screen.Bounds.Y + screen.Bounds.Height / 2 - }; - - IntPtr hMonitor = MonitorFromPoint(centerPoint, MONITOR_DEFAULTTONEAREST); - - if (hMonitor != IntPtr.Zero) - { - int result = GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, out uint dpiX, out uint dpiY); - if (result == 0) // S_OK - { - // Convert from DPI to scale factor (96 DPI = 100% = 1.0) - return (dpiX / 96.0, dpiY / 96.0); - } - } - } - catch - { - // Fall through to default - } - - // Fallback: return 1.0 (100% scaling) - return (1.0, 1.0); - } - - private void BrightnessUp_Click(object sender, RoutedEventArgs e) - { - IncreaseBrightness(); - } - - private void BrightnessDown_Click(object sender, RoutedEventArgs e) - { - DecreaseBrightness(); - } - - private void Close_Click(object sender, RoutedEventArgs e) - { - System.Windows.Application.Current.Shutdown(); - } - - private const int GWL_EXSTYLE = -20; - private const int WS_EX_TRANSPARENT = 0x00000020; - private const int WS_EX_LAYERED = 0x00080000; - - [DllImport("user32.dll")] - private static extern int GetWindowLong(IntPtr hwnd, int index); - - [DllImport("user32.dll")] - private static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle); +using System.IO; +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Media.Effects; +using System.Windows.Shapes; +using System.Windows.Threading; +using MediaColor = System.Windows.Media.Color; + +namespace WindowsEdgeLight; + +public partial class MainWindow : Window +{ + private bool isLightOn = true; + private double currentOpacity = 1.0; // Full brightness by default + private const double OpacityStep = 0.15; + private const double MinOpacity = 0.2; + private const double MaxOpacity = 1.0; + + + // Color temperature ("cool" blue-ish to "warm" amber-ish) + // We'll model this as a simple 0-1 slider where 0 = coolest, 1 = warmest. + private double _colorTemperature = 0.5; + private const double ColorTempStep = 0.1; + private const double MinColorTemp = 0.0; + private const double MaxColorTemp = 1.0; + + // DPI Scale + private double _dpiScaleX = 1.0; + private double _dpiScaleY = 1.0; + + private bool _isManualMonitorSwitch = false; + + private NotifyIcon? notifyIcon; + private ControlWindow? controlWindow; + // Tracks whether the control window should be visible (controls initial visibility and toggle state) + private bool isControlWindowVisible = true; + // Session-only: once the user drags the control toolbar, stop auto-repositioning it. + private bool controlWindowManuallyMoved = false; + private ToolStripMenuItem? toggleControlsMenuItem; + private ToolStripMenuItem? excludeFromCaptureMenuItem; + + // Application settings + private AppSettings settings = new AppSettings(); + + private sealed class HoleCache + { + public Geometry? BaseGeometry { get; set; } + public EllipseGeometry? Hole { get; set; } + public CombinedGeometry? Combined { get; set; } + } + + private class MonitorWindowContext + { + public Window Window { get; set; } = null!; + public Screen Screen { get; set; } = null!; + public System.Windows.Shapes.Path BorderPath { get; set; } = null!; + public Ellipse HoverRing { get; set; } = null!; + public Geometry BaseGeometry { get; set; } = null!; + public Rect FrameOuterRect { get; set; } + public Rect FrameInnerRect { get; set; } + public double PathOffsetX { get; set; } + public double PathOffsetY { get; set; } + public double DpiScaleX { get; set; } = 1.0; + public double DpiScaleY { get; set; } = 1.0; + public HoleCache HoleCache { get; } = new(); + } + + // Monitor management + private int currentMonitorIndex = 0; + private Screen[] availableMonitors = Array.Empty(); + private bool showOnAllMonitors = false; + private List additionalMonitorWindows = new List(); + + // Global hotkey IDs + private const int HOTKEY_TOGGLE = 1; + private const int HOTKEY_BRIGHTNESS_UP = 2; + private const int HOTKEY_BRIGHTNESS_DOWN = 3; + + [DllImport("user32.dll")] + private static extern int GetSystemMetrics(int nIndex); + private const int SM_CXSCREEN = 0; + private const int SM_CYSCREEN = 1; + + [DllImport("user32.dll")] + private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); + + [DllImport("user32.dll")] + private static extern bool UnregisterHotKey(IntPtr hWnd, int id); + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool SetWindowDisplayAffinity(IntPtr hWnd, uint dwAffinity); + + private const uint WDA_NONE = 0x00000000; + private const uint WDA_EXCLUDEFROMCAPTURE = 0x00000011; + + [DllImport("user32.dll")] + private static extern IntPtr MonitorFromPoint(POINT pt, uint dwFlags); + + [DllImport("shcore.dll")] + private static extern int GetDpiForMonitor(IntPtr hmonitor, int dpiType, out uint dpiX, out uint dpiY); + + private const int MDT_EFFECTIVE_DPI = 0; + private const uint MONITOR_DEFAULTTONEAREST = 2; + + [StructLayout(LayoutKind.Sequential)] + private struct POINT + { + public int x; // lowercase to match existing usage + public int y; + } + + // Mouse hook P/Invoke declarations + [DllImport("user32.dll", SetLastError = true)] + private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId); + + [DllImport("user32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool UnhookWindowsHookEx(IntPtr hhk); + + [DllImport("user32.dll")] + private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr GetModuleHandle(string lpModuleName); + + private const int WH_MOUSE_LL = 14; + private const int WM_MOUSEMOVE = 0x0200; + + [StructLayout(LayoutKind.Sequential)] + private struct MSLLHOOKSTRUCT + { + public POINT pt; + public uint mouseData; + public uint flags; + public uint time; + public IntPtr dwExtraInfo; + } + + private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam); + + // Mouse hook management + private IntPtr mouseHookHandle = IntPtr.Zero; + private LowLevelMouseProc? mouseHookCallback; + + private Rect? frameOuterRect; + private Rect? frameInnerRect; + private readonly Ellipse? hoverCursorRing; + // Added fields for hole effect + private Geometry? baseFrameGeometry; // original frame geometry (outer minus inner) + private double pathOffsetX; // offset of geometry within window + private double pathOffsetY; + private readonly HoleCache primaryHoleCache = new(); + + private static readonly MediaColor CoolColor = MediaColor.FromRgb(220, 235, 255); + private static readonly MediaColor WarmColor = MediaColor.FromRgb(255, 220, 180); + + private const uint MOD_CONTROL = 0x0002; + private const uint MOD_SHIFT = 0x0004; + private const uint VK_L = 0x4C; + private const uint VK_UP = 0x26; + private const uint VK_DOWN = 0x28; + + public MainWindow() + { + InitializeComponent(); + hoverCursorRing = FindName("HoverCursorRing") as Ellipse; + + // Load settings + settings = AppSettings.Load(); + + // Restore persisted state + isLightOn = settings.IsLightOn; + currentOpacity = Math.Max(MinOpacity, Math.Min(MaxOpacity, settings.Brightness)); + _colorTemperature = Math.Max(MinColorTemp, Math.Min(MaxColorTemp, settings.ColorTemperature)); + + // Save back if values were clamped + if (currentOpacity != settings.Brightness || _colorTemperature != settings.ColorTemperature) + { + settings.Brightness = currentOpacity; + settings.ColorTemperature = _colorTemperature; + settings.Save(); + } + + SetupNotifyIcon(); + } + + private void SetupNotifyIcon() + { + notifyIcon = new NotifyIcon(); + + // Load icon from embedded resource or file + try + { + var iconPath = System.IO.Path.Combine(AppContext.BaseDirectory, "ringlight_cropped.ico"); + if (File.Exists(iconPath)) + { + notifyIcon.Icon = new System.Drawing.Icon(iconPath); + } + else + { + // Try application icon from exe + var appIcon = System.Drawing.Icon.ExtractAssociatedIcon(Environment.ProcessPath ?? System.Reflection.Assembly.GetExecutingAssembly().Location); + notifyIcon.Icon = appIcon ?? System.Drawing.SystemIcons.Application; + } + } + catch (Exception) + { + // Fallback to default icon if loading fails + notifyIcon.Icon = System.Drawing.SystemIcons.Application; + } + + notifyIcon.Text = "Windows Edge Light - Right-click for options"; + notifyIcon.Visible = true; + + var contextMenu = new ContextMenuStrip(); + contextMenu.Items.Add("📋 Keyboard Shortcuts", null, (s, e) => ShowHelp()); + contextMenu.Items.Add(new ToolStripSeparator()); + contextMenu.Items.Add("💡 Toggle Light (Ctrl+Shift+L)", null, (s, e) => ToggleLight()); + contextMenu.Items.Add("🔆 Brightness Up (Ctrl+Shift+↑)", null, (s, e) => IncreaseBrightness()); + contextMenu.Items.Add("🔅 Brightness Down (Ctrl+Shift+↓)", null, (s, e) => DecreaseBrightness()); + contextMenu.Items.Add(new ToolStripSeparator()); + contextMenu.Items.Add("🔥 K- Warmer Light", null, (s, e) => IncreaseColorTemperature()); + contextMenu.Items.Add("❄️ K+ Cooler Light", null, (s, e) => DecreaseColorTemperature()); + contextMenu.Items.Add(new ToolStripSeparator()); + contextMenu.Items.Add("🖥️ Switch Monitor", null, (s, e) => MoveToNextMonitor()); + contextMenu.Items.Add("🖥️🖥️ Toggle All Monitors", null, (s, e) => ToggleAllMonitors()); + contextMenu.Items.Add(new ToolStripSeparator()); + + // Add toggle controls menu item - text will be set by UpdateTrayMenuToggleControlsText + toggleControlsMenuItem = new ToolStripMenuItem("🎛️ Hide Controls", null, (s, e) => ToggleControlsVisibility()); + contextMenu.Items.Add(toggleControlsMenuItem); + contextMenu.Items.Add("📍 Reset Control Bar Position", null, (s, e) => ResetControlWindowPosition()); + + // Add exclude from capture menu item with checkmark + excludeFromCaptureMenuItem = new ToolStripMenuItem("🎥 Exclude from Screen Capture", null, (s, e) => ToggleExcludeFromCapture()); + excludeFromCaptureMenuItem.CheckOnClick = true; + excludeFromCaptureMenuItem.Checked = settings.ExcludeFromCapture; + contextMenu.Items.Add(excludeFromCaptureMenuItem); + + contextMenu.Items.Add(new ToolStripSeparator()); + contextMenu.Items.Add("✖ Exit", null, (s, e) => System.Windows.Application.Current.Shutdown()); + + notifyIcon.ContextMenuStrip = contextMenu; + notifyIcon.DoubleClick += (s, e) => ShowHelp(); + + // Set initial menu text based on current state + UpdateTrayMenuToggleControlsText(); + } + + private void ShowHelp() + { + var version = System.Reflection.Assembly.GetExecutingAssembly() + .GetName().Version?.ToString() ?? "Unknown"; + + var helpMessage = $@"Windows Edge Light - Keyboard Shortcuts + +💡 Toggle Light: Ctrl + Shift + L +🔆 Brightness Up: Ctrl + Shift + ↑ +🔅 Brightness Down: Ctrl + Shift + ↓ + +💡 Features: +• Click-through overlay - won't interfere with your work +• Global hotkeys work from any application +• Right-click taskbar icon for full menu +• Control toolbar with brightness, color temp, and monitor options +• Color temperature controls (🔥 warmer, ❄️ cooler) +• Switch between monitors or show on all monitors +• Exclude from screen capture (🎥) - invisible in Teams/Zoom sharing + +Created by Scott Hanselman +Version {version}"; + + System.Windows.MessageBox.Show(helpMessage, "Windows Edge Light - Help", + MessageBoxButton.OK, MessageBoxImage.Information); + } + + private void SetupWindow() + { + // Initialize available monitors on first setup + if (availableMonitors.Length == 0) + { + RefreshAvailableMonitors(); + + // Find the primary monitor index + for (int i = 0; i < availableMonitors.Length; i++) + { + if (availableMonitors[i].Primary) + { + currentMonitorIndex = i; + break; + } + } + } + + var targetScreen = GetCurrentScreen(); + if (targetScreen == null) return; + + SetupWindowForScreen(targetScreen); + } + + private void SetupWindowForScreen(Screen screen) + { + // Use WorkingArea instead of Bounds to exclude taskbar + var workingArea = screen.WorkingArea; + + // Get DPI scale factor for the target screen + (_dpiScaleX, _dpiScaleY) = GetDpiForScreen(screen); + + // Convert physical pixels to WPF DIPs + this.Left = workingArea.X / _dpiScaleX; + this.Top = workingArea.Y / _dpiScaleY; + this.Width = workingArea.Width / _dpiScaleX; + this.Height = workingArea.Height / _dpiScaleY; + this.WindowState = System.Windows.WindowState.Normal; + } + + private void Window_Loaded(object sender, RoutedEventArgs e) + { + SetupWindow(); + CreateFrameGeometry(); + CreateControlWindow(); + + var hwnd = new WindowInteropHelper(this).Handle; + int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); + SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT | WS_EX_LAYERED); + + RegisterGlobalHotKeys(hwnd); + + // Hook into Windows message processing + HwndSource source = HwndSource.FromHwnd(hwnd); + source.AddHook(HwndHook); + + // Listen for window size/location changes (docking/undocking) + this.SizeChanged += Window_SizeChanged; + this.LocationChanged += Window_LocationChanged; + + // Apply exclude from capture setting + ApplyExcludeFromCapture(); + + // Apply persisted brightness and color temperature + EdgeLightBorder.Opacity = currentOpacity; + SetColorTemperature(_colorTemperature); + + // Apply persisted on/off state + if (!isLightOn) + { + EdgeLightBorder.Visibility = Visibility.Collapsed; + } + + InstallMouseHook(); + } + + private void RegisterGlobalHotKeys(IntPtr hwnd) + { + var failedHotKeys = new List(); + + if (!RegisterHotKey(hwnd, HOTKEY_TOGGLE, MOD_CONTROL | MOD_SHIFT, VK_L)) + { + failedHotKeys.Add("Toggle Light (Ctrl+Shift+L)"); + } + + if (!RegisterHotKey(hwnd, HOTKEY_BRIGHTNESS_UP, MOD_CONTROL | MOD_SHIFT, VK_UP)) + { + failedHotKeys.Add("Brightness Up (Ctrl+Shift+Up)"); + } + + if (!RegisterHotKey(hwnd, HOTKEY_BRIGHTNESS_DOWN, MOD_CONTROL | MOD_SHIFT, VK_DOWN)) + { + failedHotKeys.Add("Brightness Down (Ctrl+Shift+Down)"); + } + + if (failedHotKeys.Count > 0) + { + notifyIcon?.ShowBalloonTip( + 5000, + "Windows Edge Light hotkey conflict", + "Some keyboard shortcuts could not be registered because another app is using them:\n\n" + + string.Join("\n", failedHotKeys) + + "\n\nUse the tray menu controls instead.", + ToolTipIcon.Warning); + } + } + + private void InstallMouseHook() + { + // Store callback to prevent garbage collection + mouseHookCallback = MouseHookProc; + + using var curProcess = System.Diagnostics.Process.GetCurrentProcess(); + using var curModule = curProcess.MainModule; + if (curModule != null) + { + mouseHookHandle = SetWindowsHookEx(WH_MOUSE_LL, mouseHookCallback, + GetModuleHandle(curModule.ModuleName), 0); + } + } + + private void UninstallMouseHook() + { + if (mouseHookHandle != IntPtr.Zero) + { + UnhookWindowsHookEx(mouseHookHandle); + mouseHookHandle = IntPtr.Zero; + } + } + + private IntPtr MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) + { + if (nCode >= 0 && wParam == (IntPtr)WM_MOUSEMOVE) + { + var hookStruct = Marshal.PtrToStructure(lParam); + + // Dispatch to UI thread for WPF operations + Dispatcher.BeginInvoke(new Action(() => + { + HandleMouseMove(hookStruct.pt.x, hookStruct.pt.y); + }), System.Windows.Threading.DispatcherPriority.Input); + } + + return CallNextHookEx(mouseHookHandle, nCode, wParam, lParam); + } + + private void HandleMouseMove(int screenX, int screenY) + { + if (!isLightOn) + { + if (EdgeLightBorder.Visibility != Visibility.Collapsed) + { + EdgeLightBorder.Visibility = Visibility.Collapsed; + } + + if (hoverCursorRing != null && hoverCursorRing.Visibility != Visibility.Collapsed) + { + hoverCursorRing.Visibility = Visibility.Collapsed; + } + // Restore original geometry if previously punched + if (baseFrameGeometry != null && EdgeLightBorder.Data != baseFrameGeometry) + { + EdgeLightBorder.Data = baseFrameGeometry; + } + + // Also handle additional windows + foreach (var ctx in additionalMonitorWindows) + { + if (ctx.BorderPath.Visibility != Visibility.Collapsed) + ctx.BorderPath.Visibility = Visibility.Collapsed; + if (ctx.HoverRing.Visibility != Visibility.Collapsed) + ctx.HoverRing.Visibility = Visibility.Collapsed; + if (ctx.BorderPath.Data != ctx.BaseGeometry) + ctx.BorderPath.Data = ctx.BaseGeometry; + } + + return; + } + + // --- Main Window Logic --- + if (frameOuterRect != null && frameInnerRect != null && hoverCursorRing != null && baseFrameGeometry != null) + { + var screen = GetCurrentScreen(); + if (screen != null) + { + ApplyHolePunchEffect( + screenX, screenY, + screen, + _dpiScaleX, _dpiScaleY, + frameOuterRect.Value, frameInnerRect.Value, + hoverCursorRing, + EdgeLightBorder, + baseFrameGeometry, + pathOffsetX, pathOffsetY, + (ring, x, y) => { Canvas.SetLeft(ring, x); Canvas.SetTop(ring, y); }, + primaryHoleCache + ); + } + } + + // --- Additional Windows Logic --- + foreach (var ctx in additionalMonitorWindows) + { + try + { + ApplyHolePunchEffect( + screenX, screenY, + ctx.Screen, + ctx.DpiScaleX, ctx.DpiScaleY, + ctx.FrameOuterRect, ctx.FrameInnerRect, + ctx.HoverRing, + ctx.BorderPath, + ctx.BaseGeometry, + ctx.PathOffsetX, ctx.PathOffsetY, + (ring, x, y) => { ring.Margin = new Thickness(x, y, 0, 0); }, + ctx.HoleCache + ); + } + catch (InvalidOperationException) + { + // Can happen if window is closing or not ready + } + } + } + + private void ApplyHolePunchEffect( + int screenX, int screenY, + Screen screen, + double dpiScaleX, double dpiScaleY, + Rect frameOuterRect, Rect frameInnerRect, + Ellipse hoverRing, + System.Windows.Shapes.Path borderPath, + Geometry baseGeometry, + double pathOffsetX, double pathOffsetY, + Action positionRing, + HoleCache holeCache) + { + // Manual coordinate calculation to avoid PointFromScreen issues across monitors/DPIs + // We positioned the window using dpiScaleX/Y relative to the screen WorkingArea. + double relX = (screenX - screen.WorkingArea.X) / dpiScaleX; + double relY = (screenY - screen.WorkingArea.Y) / dpiScaleY; + var windowPt = new System.Windows.Point(relX, relY); + + // Existing frame band detection (outer minus inner) + bool inFrameBand = frameOuterRect.Contains(windowPt) && !frameInnerRect.Contains(windowPt); + + // Early detection zone just inside the inner edge: a band with thickness = hole radius (cursor ring radius) + double ringDiameter = hoverRing.Width; + double holeRadius = ringDiameter / 2; // match ring size + var innerProximityRect = new Rect( + frameInnerRect.X + holeRadius, + frameInnerRect.Y + holeRadius, + frameInnerRect.Width - (holeRadius * 2), + frameInnerRect.Height - (holeRadius * 2)); + + // Near from inside means inside innerRect but within holeRadius of its edge (i.e., not deep inside innerProximityRect) + bool nearFromInside = frameInnerRect.Contains(windowPt) && !innerProximityRect.Contains(windowPt); + + bool overFrame = inFrameBand || nearFromInside; + + if (overFrame) + { + positionRing(hoverRing, windowPt.X - ringDiameter / 2, windowPt.Y - ringDiameter / 2); + + if (hoverRing.Visibility != Visibility.Visible) + { + hoverRing.Visibility = Visibility.Visible; + } + + // Punch a transparent hole under the ring by excluding a circle geometry from the frame + // Convert window coordinates to geometry local coordinates by subtracting stored offsets + var localCenter = new System.Windows.Point(windowPt.X - pathOffsetX, windowPt.Y - pathOffsetY); + if (holeCache.BaseGeometry != baseGeometry || + holeCache.Hole == null || + holeCache.Hole.RadiusX != holeRadius || + holeCache.Combined == null) + { + holeCache.BaseGeometry = baseGeometry; + holeCache.Hole = new EllipseGeometry(localCenter, holeRadius, holeRadius); + holeCache.Combined = new CombinedGeometry(GeometryCombineMode.Exclude, baseGeometry, holeCache.Hole); + } + else + { + holeCache.Hole.Center = localCenter; + } + + borderPath.Data = holeCache.Combined; + } + else + { + if (hoverRing.Visibility != Visibility.Collapsed) + { + hoverRing.Visibility = Visibility.Collapsed; + } + + if (borderPath.Visibility != Visibility.Visible) + { + borderPath.Visibility = Visibility.Visible; + } + // Restore original geometry (remove hole) + if (baseGeometry != null && borderPath.Data != baseGeometry) + { + borderPath.Data = baseGeometry; + } + } + } + + private void CreateControlWindow() + { + controlWindow = new ControlWindow(this); + RepositionControlWindow(); + + // Only show if controls are supposed to be visible + if (isControlWindowVisible) + { + controlWindow.Show(); + } + } + + private void CreateFrameGeometry() + { + // Get actual dimensions (accounting for margin) + double width = this.ActualWidth - 40; // 20px margin on each side + double height = this.ActualHeight - 40; + + const double frameThickness = 80; + const double outerRadius = 100; // Extra rounded like macOS + const double innerRadius = 60; // Keep proportional + + // Outer rounded rectangle + var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); + + // Inner rounded rectangle + var innerRect = new RectangleGeometry( + new Rect(frameThickness, frameThickness, + width - (frameThickness * 2), + height - (frameThickness * 2)), + innerRadius, innerRadius); + + // Combine: outer minus inner = frame + var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); + baseFrameGeometry = frameGeometry; // store original + EdgeLightBorder.Data = frameGeometry; + pathOffsetX = (ActualWidth - width) / 2.0; // store offsets for local coordinate conversion + pathOffsetY = (ActualHeight - height) / 2.0; + // Expand outer and contract inner rects for earlier hover detection based on ring hole radius. + double ringDiameter = hoverCursorRing?.Width ?? 0; + double holeRadius = ringDiameter / 2.0; + frameOuterRect = new Rect(pathOffsetX - holeRadius, pathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); + frameInnerRect = new Rect(pathOffsetX + frameThickness + holeRadius, pathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); + } + + private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + const int WM_HOTKEY = 0x0312; + + if (msg == WM_HOTKEY) + { + int hotkeyId = wParam.ToInt32(); + + switch (hotkeyId) + { + case HOTKEY_TOGGLE: + ToggleLight(); + handled = true; + break; + case HOTKEY_BRIGHTNESS_UP: + IncreaseBrightness(); + handled = true; + break; + case HOTKEY_BRIGHTNESS_DOWN: + DecreaseBrightness(); + handled = true; + break; + } + } + + return IntPtr.Zero; + } + + protected override void OnDpiChanged(DpiScale oldDpi, DpiScale newDpi) + { + base.OnDpiChanged(oldDpi, newDpi); + + _dpiScaleX = newDpi.DpiScaleX; + _dpiScaleY = newDpi.DpiScaleY; + + // Ensure window covers the current monitor correctly with new DPI + if (availableMonitors.Length > 0) + { + // Re-verify which monitor we are on, as we might have just moved + UpdateCurrentMonitorIndex(); + + if (currentMonitorIndex < availableMonitors.Length) + { + var screen = availableMonitors[currentMonitorIndex]; + var workingArea = screen.WorkingArea; + + // Only update if significantly different to avoid loops + double newLeft = workingArea.X / _dpiScaleX; + double newTop = workingArea.Y / _dpiScaleY; + double newWidth = workingArea.Width / _dpiScaleX; + double newHeight = workingArea.Height / _dpiScaleY; + + if (Math.Abs(this.Left - newLeft) > 1 || Math.Abs(this.Top - newTop) > 1 || + Math.Abs(this.Width - newWidth) > 1 || Math.Abs(this.Height - newHeight) > 1) + { + this.Left = newLeft; + this.Top = newTop; + this.Width = newWidth; + this.Height = newHeight; + } + } + } + } + + protected override void OnClosed(EventArgs e) + { + UninstallMouseHook(); + + var hwnd = new WindowInteropHelper(this).Handle; + UnregisterHotKey(hwnd, HOTKEY_TOGGLE); + UnregisterHotKey(hwnd, HOTKEY_BRIGHTNESS_UP); + UnregisterHotKey(hwnd, HOTKEY_BRIGHTNESS_DOWN); + + if (notifyIcon != null) + { + notifyIcon.Visible = false; + notifyIcon.Dispose(); + } + + HideAdditionalMonitorWindows(); + controlWindow?.Close(); + + base.OnClosed(e); + } + + private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) + { + if (e.Key == Key.L && + (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && + (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) + { + ToggleLight(); + } + else if (e.Key == Key.Escape) + { + System.Windows.Application.Current.Shutdown(); + } + } + + private void Toggle_Click(object sender, RoutedEventArgs e) + { + ToggleLight(); + } + + private void ToggleLight() + { + isLightOn = !isLightOn; + if (isLightOn) + { + EdgeLightBorder.Visibility = Visibility.Visible; + // Restore base geometry on toggle if needed + if (baseFrameGeometry != null) + { + EdgeLightBorder.Data = baseFrameGeometry; + } + } + else + { + EdgeLightBorder.Visibility = Visibility.Collapsed; + if (hoverCursorRing != null) + { + hoverCursorRing.Visibility = Visibility.Collapsed; + } + } + + // Update all additional monitor windows + UpdateAdditionalMonitorWindows(); + + settings.IsLightOn = isLightOn; + settings.Save(); + } + + public void HandleToggle() + { + ToggleLight(); + } + + public void ToggleControlsVisibility() + { + isControlWindowVisible = !isControlWindowVisible; + + // Apply visibility change if control window exists + if (controlWindow != null) + { + if (isControlWindowVisible) + { + controlWindow.Show(); + } + else + { + controlWindow.Hide(); + } + } + // Note: If controlWindow doesn't exist yet, isControlWindowVisible state + // is preserved and will be applied when CreateControlWindow() is called + + UpdateTrayMenuToggleControlsText(); + } + + private void UpdateTrayMenuToggleControlsText() + { + if (toggleControlsMenuItem != null) + { + toggleControlsMenuItem.Text = isControlWindowVisible ? "🎛️ Hide Controls" : "🎛️ Show Controls"; + } + } + + public void ToggleExcludeFromCapture() + { + settings.ExcludeFromCapture = !settings.ExcludeFromCapture; + settings.Save(); + + // Update menu checkmark + if (excludeFromCaptureMenuItem != null) + { + excludeFromCaptureMenuItem.Checked = settings.ExcludeFromCapture; + } + + // Apply the setting to all windows + ApplyExcludeFromCapture(); + } + + private void ApplyExcludeFromCapture() + { + var hwnd = new WindowInteropHelper(this).Handle; + if (hwnd != IntPtr.Zero) + { + var result = SetWindowDisplayAffinity(hwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); + if (!result) + { + var error = Marshal.GetLastWin32Error(); + System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for main window. Error: {error}"); + } + } + + // Apply to control window + if (controlWindow != null) + { + var controlHwnd = new WindowInteropHelper(controlWindow).Handle; + if (controlHwnd != IntPtr.Zero) + { + var result = SetWindowDisplayAffinity(controlHwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); + if (!result) + { + var error = Marshal.GetLastWin32Error(); + System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for control window. Error: {error}"); + } + } + } + + // Apply to all additional monitor windows + foreach (var ctx in additionalMonitorWindows) + { + var monitorHwnd = new WindowInteropHelper(ctx.Window).Handle; + if (monitorHwnd != IntPtr.Zero) + { + var result = SetWindowDisplayAffinity(monitorHwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); + if (!result) + { + var error = Marshal.GetLastWin32Error(); + System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for monitor window. Error: {error}"); + } + } + } + } + + public void IncreaseBrightness() + { + SetBrightness(currentOpacity + OpacityStep); + } + + public void DecreaseBrightness() + { + SetBrightness(currentOpacity - OpacityStep); + } + + public void SetBrightness(double value, bool save = true) + { + currentOpacity = Math.Max(MinOpacity, Math.Min(MaxOpacity, value)); + EdgeLightBorder.Opacity = currentOpacity; + UpdateAdditionalMonitorWindows(); + + if (save) + { + settings.Brightness = currentOpacity; + settings.Save(); + } + } + + private void UpdateAdditionalMonitorWindows() + { + foreach (var ctx in additionalMonitorWindows) + { + var path = ctx.BorderPath; + path.Opacity = currentOpacity; + path.Visibility = isLightOn ? Visibility.Visible : Visibility.Collapsed; + ApplyColorTemperature(path); + } + } + + public void IncreaseColorTemperature() + { + SetColorTemperature(_colorTemperature + ColorTempStep); + } + + public void DecreaseColorTemperature() + { + SetColorTemperature(_colorTemperature - ColorTempStep); + } + + public void SetColorTemperature(double value, bool save = true) + { + _colorTemperature = Math.Max(MinColorTemp, Math.Min(MaxColorTemp, value)); + ApplyColorTemperature(EdgeLightBorder); + + // Update all additional monitor windows + UpdateAdditionalMonitorWindows(); + + if (save) + { + settings.ColorTemperature = _colorTemperature; + settings.Save(); + } + } + + public void MoveToNextMonitor() + { + // If in all monitors mode, do nothing + if (showOnAllMonitors) return; + + // Refresh monitor list in case of hot-plug/unplug + RefreshAvailableMonitors(); + + if (availableMonitors.Length <= 1) + { + return; + } + + // Ensure currentMonitorIndex is accurate before moving + UpdateCurrentMonitorIndex(); + + _isManualMonitorSwitch = true; + try + { + // Cycle to next monitor + currentMonitorIndex = (currentMonitorIndex + 1) % availableMonitors.Length; + var targetScreen = availableMonitors[currentMonitorIndex]; + + // Reposition main window to new monitor using physical coordinates to trigger DPI change correctly + var hwnd = new WindowInteropHelper(this).Handle; + SetWindowPos(hwnd, IntPtr.Zero, + targetScreen.WorkingArea.X, targetScreen.WorkingArea.Y, + targetScreen.WorkingArea.Width, targetScreen.WorkingArea.Height, + SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); + + // Force a size update if DPI didn't change (SetWindowPos might not trigger OnDpiChanged) + // If DPI changed, OnDpiChanged will handle it. + // But we can't easily know if OnDpiChanged fired yet. + // However, setting properties to the same value is cheap in WPF. + // We need to ensure we use the NEW DPI if it changed. + // OnDpiChanged updates _dpiScaleX/Y. + + // If we are on the same thread, OnDpiChanged (via WM_DPICHANGED) should have fired synchronously during SetWindowPos. + // So _dpiScaleX/Y should be up to date. + + double newLeft = targetScreen.WorkingArea.X / _dpiScaleX; + double newTop = targetScreen.WorkingArea.Y / _dpiScaleY; + double newWidth = targetScreen.WorkingArea.Width / _dpiScaleX; + double newHeight = targetScreen.WorkingArea.Height / _dpiScaleY; + + this.Left = newLeft; + this.Top = newTop; + this.Width = newWidth; + this.Height = newHeight; + } + finally + { + _isManualMonitorSwitch = false; + } + + // An explicit monitor switch should bring the controls to the selected monitor. + ResetControlWindowPosition(); + } + + [DllImport("user32.dll", SetLastError = true)] + private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); + private const uint SWP_NOZORDER = 0x0004; + private const uint SWP_NOACTIVATE = 0x0010; + private const uint SWP_FRAMECHANGED = 0x0020; + + public void ToggleAllMonitors() + { + showOnAllMonitors = !showOnAllMonitors; + + if (showOnAllMonitors) + { + ShowOnAllMonitors(); + } + else + { + HideAdditionalMonitorWindows(); + } + + controlWindow?.UpdateAllMonitorsButtonState(); + } + + private void ShowOnAllMonitors() + { + RefreshAvailableMonitors(); + + // Close any existing additional windows + HideAdditionalMonitorWindows(); + + // Create a window for each monitor except the current one (this window) + for (int i = 0; i < availableMonitors.Length; i++) + { + if (i != currentMonitorIndex) + { + var monitorCtx = CreateMonitorWindow(availableMonitors[i]); + additionalMonitorWindows.Add(monitorCtx); + monitorCtx.Window.Show(); + } + } + } + + private void HideAdditionalMonitorWindows() + { + foreach (var ctx in additionalMonitorWindows) + { + ctx.Window.Close(); + } + additionalMonitorWindows.Clear(); + } + + private MonitorWindowContext CreateMonitorWindow(Screen screen) + { + var window = new Window + { + Title = "Windows Edge Light", + AllowsTransparency = true, + Background = System.Windows.Media.Brushes.Transparent, + ResizeMode = ResizeMode.NoResize, + ShowInTaskbar = false, + Topmost = true, + WindowStyle = WindowStyle.None + }; + + // Position on the target screen + var workingArea = screen.WorkingArea; + + // Get the correct DPI scale for THIS specific screen + var (screenDpiX, screenDpiY) = GetDpiForScreen(screen); + + // Convert physical pixels to WPF DIPs using the correct per-monitor DPI + window.Left = workingArea.X / screenDpiX; + window.Top = workingArea.Y / screenDpiY; + window.Width = workingArea.Width / screenDpiX; + window.Height = workingArea.Height / screenDpiY; + + // Create the grid and edge light border + var grid = new System.Windows.Controls.Grid { IsHitTestVisible = false }; + var path = new System.Windows.Shapes.Path + { + HorizontalAlignment = System.Windows.HorizontalAlignment.Center, + VerticalAlignment = System.Windows.VerticalAlignment.Center, + Stretch = System.Windows.Media.Stretch.None, + Opacity = currentOpacity, + Visibility = isLightOn ? Visibility.Visible : Visibility.Collapsed + }; + + var temperatureColor = GetColorForTemperature(_colorTemperature); + var gradient = new LinearGradientBrush + { + StartPoint = new System.Windows.Point(0, 0), + EndPoint = new System.Windows.Point(1, 1) + }; + gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 0.0)); + gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.3)); + gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.5)); + gradient.GradientStops.Add(new GradientStop(temperatureColor, 0.7)); + gradient.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromRgb(255, 255, 255), 1.0)); + path.Fill = gradient; + + // Add drop shadow effect + path.Effect = new DropShadowEffect + { + BlurRadius = 76, + Opacity = 1, + ShadowDepth = 0, + Color = temperatureColor + }; + + // Create hover ring (Ellipse) + var hoverRing = new Ellipse + { + Width = 140, + Height = 140, + Fill = System.Windows.Media.Brushes.Transparent, + Visibility = Visibility.Collapsed, + HorizontalAlignment = System.Windows.HorizontalAlignment.Left, + VerticalAlignment = System.Windows.VerticalAlignment.Top + }; + // Add drop shadow to ring - actually main window doesn't seem to have this on the ring itself? + // Main window XAML doesn't show effect on HoverCursorRing. + // So removing effect to match. + + // Create frame geometry + double width = window.Width - 40; + double height = window.Height - 40; + const double frameThickness = 80; + const double outerRadius = 100; + const double innerRadius = 60; + + var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); + var innerRect = new RectangleGeometry( + new Rect(frameThickness, frameThickness, + width - (frameThickness * 2), + height - (frameThickness * 2)), + innerRadius, innerRadius); + + var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); + path.Data = frameGeometry; + + grid.Children.Add(path); + grid.Children.Add(hoverRing); + window.Content = grid; + + // Calculate geometry data for hole punch + double pathOffsetX = (window.Width - width) / 2.0; + double pathOffsetY = (window.Height - height) / 2.0; + + double ringDiameter = hoverRing.Width; + double holeRadius = ringDiameter / 2.0; + var frameOuterRect = new Rect(pathOffsetX - holeRadius, pathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); + var frameInnerRect = new Rect(pathOffsetX + frameThickness + holeRadius, pathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); + + var ctx = new MonitorWindowContext + { + Window = window, + Screen = screen, + BorderPath = path, + HoverRing = hoverRing, + BaseGeometry = frameGeometry, + FrameOuterRect = frameOuterRect, + FrameInnerRect = frameInnerRect, + PathOffsetX = pathOffsetX, + PathOffsetY = pathOffsetY, + DpiScaleX = screenDpiX, // Use calculated DPI for this screen + DpiScaleY = screenDpiY + }; + + // Make window click-through and handle DPI + window.Loaded += (s, e) => + { + var hwnd = new WindowInteropHelper(window).Handle; + int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); + SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT | WS_EX_LAYERED); + + // Apply exclude from capture setting + var result = SetWindowDisplayAffinity(hwnd, settings.ExcludeFromCapture ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE); + if (!result) + { + var error = Marshal.GetLastWin32Error(); + System.Diagnostics.Debug.WriteLine($"Failed to set display affinity for monitor window during creation. Error: {error}"); + } + + // Verify and update DPI if WPF reports a different value after window is loaded + var source = PresentationSource.FromVisual(window); + if (source != null) + { + double dpiX = source.CompositionTarget.TransformToDevice.M11; + double dpiY = source.CompositionTarget.TransformToDevice.M22; + + // Only reposition if DPI changed significantly from our initial calculation + if (Math.Abs(dpiX - ctx.DpiScaleX) > 0.01 || Math.Abs(dpiY - ctx.DpiScaleY) > 0.01) + { + ctx.DpiScaleX = dpiX; + ctx.DpiScaleY = dpiY; + + // Reposition/Resize with correct DPI + window.Left = screen.WorkingArea.X / dpiX; + window.Top = screen.WorkingArea.Y / dpiY; + window.Width = screen.WorkingArea.Width / dpiX; + window.Height = screen.WorkingArea.Height / dpiY; + + // Recalculate geometry for new window size + UpdateMonitorGeometry(ctx); + } + } + }; + + window.DpiChanged += (s, dpiArgs) => + { + ctx.DpiScaleX = dpiArgs.NewDpi.DpiScaleX; + ctx.DpiScaleY = dpiArgs.NewDpi.DpiScaleY; + + window.Left = screen.WorkingArea.X / ctx.DpiScaleX; + window.Top = screen.WorkingArea.Y / ctx.DpiScaleY; + window.Width = screen.WorkingArea.Width / ctx.DpiScaleX; + window.Height = screen.WorkingArea.Height / ctx.DpiScaleY; + + UpdateMonitorGeometry(ctx); + }; + + return ctx; + } + + private void UpdateMonitorGeometry(MonitorWindowContext ctx) + { + double width = ctx.Window.Width - 40; + double height = ctx.Window.Height - 40; + const double frameThickness = 80; + const double outerRadius = 100; + const double innerRadius = 60; + + var outerRect = new RectangleGeometry(new Rect(0, 0, width, height), outerRadius, outerRadius); + var innerRect = new RectangleGeometry( + new Rect(frameThickness, frameThickness, + width - (frameThickness * 2), + height - (frameThickness * 2)), + innerRadius, innerRadius); + + var frameGeometry = new CombinedGeometry(GeometryCombineMode.Exclude, outerRect, innerRect); + + ctx.BaseGeometry = frameGeometry; + ctx.BorderPath.Data = frameGeometry; + + ctx.PathOffsetX = (ctx.Window.Width - width) / 2.0; + ctx.PathOffsetY = (ctx.Window.Height - height) / 2.0; + + double ringDiameter = ctx.HoverRing.Width; + double holeRadius = ringDiameter / 2.0; + + ctx.FrameOuterRect = new Rect(ctx.PathOffsetX - holeRadius, ctx.PathOffsetY - holeRadius, width + holeRadius * 2, height + holeRadius * 2); + ctx.FrameInnerRect = new Rect(ctx.PathOffsetX + frameThickness + holeRadius, ctx.PathOffsetY + frameThickness + holeRadius, width - (frameThickness * 2) - holeRadius * 2, height - (frameThickness * 2) - holeRadius * 2); + } + + public bool IsShowingOnAllMonitors() + { + return showOnAllMonitors; + } + + private void RepositionControlWindow() + { + if (controlWindow == null) return; + + // Respect a user-dragged position for the current session. + if (controlWindowManuallyMoved) return; + + // Position at bottom center of main window + controlWindow.Left = this.Left + (this.Width - controlWindow.Width) / 2; + controlWindow.Top = this.Top + this.Height - controlWindow.Height - 124; + } + + public void NotifyControlWindowManuallyMoved() + { + controlWindowManuallyMoved = true; + } + + public void ResetControlWindowPosition() + { + controlWindowManuallyMoved = false; + RepositionControlWindow(); + } + + public bool HasMultipleMonitors() + { + // Refresh monitor count to handle hot-plug scenarios + RefreshAvailableMonitors(); + return availableMonitors.Length > 1; + } + + public bool IsExcludeFromCaptureEnabled() + { + return settings.ExcludeFromCapture; + } + + public double GetBrightness() => currentOpacity; + + public double GetColorTemperature() => _colorTemperature; + + public void SaveAppearanceSettings() + { + settings.Brightness = currentOpacity; + settings.ColorTemperature = _colorTemperature; + settings.Save(); + } + + public bool GetIsToggleButtonVisible() => settings.ShowToggleButton; + + public bool GetIsBrightnessButtonsVisible() => settings.ShowBrightnessButtons; + + public bool GetIsColorTempButtonsVisible() => settings.ShowColorTempButtons; + + public bool GetIsControlMonitorsButtonVisible() => settings.ShowMonitorControlButtons; + + public void SetIsToggleVisible(bool isVisible) + { + settings.ShowToggleButton = isVisible; + settings.Save(); + } + + public void SetIsBrightnessButtonsVisible(bool isVisible) + { + settings.ShowBrightnessButtons = isVisible; + settings.Save(); + } + + public void SetIsColorTempButtonsVisible(bool isVisible) + { + settings.ShowColorTempButtons = isVisible; + settings.Save(); + } + + public void SetIsControlMonitorsButtonVisible(bool isVisible) + { + settings.ShowMonitorControlButtons = isVisible; + settings.Save(); + } + + private void Window_SizeChanged(object sender, SizeChangedEventArgs e) + { + // Recreate geometry when window size changes (e.g., different monitor resolution) + if (EdgeLightBorder != null) + { + CreateFrameGeometry(); + } + + // Reposition control window + RepositionControlWindow(); + + // Update which monitor we're actually on + UpdateCurrentMonitorIndex(); + } + + private void Window_LocationChanged(object? sender, EventArgs e) + { + // Reposition control window when main window moves + RepositionControlWindow(); + + // Update which monitor we're actually on + UpdateCurrentMonitorIndex(); + } + + private void UpdateCurrentMonitorIndex() + { + // If we are manually switching, trust the index we set explicitly + if (_isManualMonitorSwitch) return; + + RefreshAvailableMonitors(); + + if (availableMonitors.Length == 0) return; + + try + { + // Use PointToScreen to get accurate physical coordinates of the window center + // This handles DPI scaling correctly unlike manual calculation + var centerPoint = this.PointToScreen(new System.Windows.Point(this.ActualWidth / 2, this.ActualHeight / 2)); + var drawingPoint = new System.Drawing.Point((int)centerPoint.X, (int)centerPoint.Y); + + for (int i = 0; i < availableMonitors.Length; i++) + { + if (availableMonitors[i].Bounds.Contains(drawingPoint)) + { + currentMonitorIndex = i; + break; + } + } + } + catch (InvalidOperationException) + { + // Window might not be loaded or visible yet + } + } + + private void RefreshAvailableMonitors() + { + availableMonitors = Screen.AllScreens; + currentMonitorIndex = availableMonitors.Length == 0 + ? 0 + : Math.Clamp(currentMonitorIndex, 0, availableMonitors.Length - 1); + } + + private Screen? GetCurrentScreen() + { + if (availableMonitors.Length == 0) + { + return Screen.PrimaryScreen; + } + + currentMonitorIndex = Math.Clamp(currentMonitorIndex, 0, availableMonitors.Length - 1); + return availableMonitors[currentMonitorIndex]; + } + + private static MediaColor GetColorForTemperature(double temperature) + { + byte Lerp(byte cool, byte warm) => (byte)(cool + ((warm - cool) * temperature)); + return MediaColor.FromRgb( + Lerp(CoolColor.R, WarmColor.R), + Lerp(CoolColor.G, WarmColor.G), + Lerp(CoolColor.B, WarmColor.B)); + } + + private void ApplyColorTemperature(System.Windows.Shapes.Path path) + { + var temperatureColor = GetColorForTemperature(_colorTemperature); + + if (path.Fill is LinearGradientBrush brush) + { + foreach (var stop in brush.GradientStops) + { + if (stop.Offset is > 0.2 and < 0.8) + { + stop.Color = temperatureColor; + } + } + } + + if (path.Effect is DropShadowEffect shadow) + { + shadow.Color = temperatureColor; + } + } + + private (double dpiScaleX, double dpiScaleY) GetDpiForScreen(Screen screen) + { + try + { + // Get monitor handle for the center of the screen + var centerPoint = new POINT + { + x = screen.Bounds.X + screen.Bounds.Width / 2, + y = screen.Bounds.Y + screen.Bounds.Height / 2 + }; + + IntPtr hMonitor = MonitorFromPoint(centerPoint, MONITOR_DEFAULTTONEAREST); + + if (hMonitor != IntPtr.Zero) + { + int result = GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, out uint dpiX, out uint dpiY); + if (result == 0) // S_OK + { + // Convert from DPI to scale factor (96 DPI = 100% = 1.0) + return (dpiX / 96.0, dpiY / 96.0); + } + } + } + catch + { + // Fall through to default + } + + // Fallback: return 1.0 (100% scaling) + return (1.0, 1.0); + } + + private void BrightnessUp_Click(object sender, RoutedEventArgs e) + { + IncreaseBrightness(); + } + + private void BrightnessDown_Click(object sender, RoutedEventArgs e) + { + DecreaseBrightness(); + } + + private void Close_Click(object sender, RoutedEventArgs e) + { + System.Windows.Application.Current.Shutdown(); + } + + private const int GWL_EXSTYLE = -20; + private const int WS_EX_TRANSPARENT = 0x00000020; + private const int WS_EX_LAYERED = 0x00080000; + + [DllImport("user32.dll")] + private static extern int GetWindowLong(IntPtr hwnd, int index); + + [DllImport("user32.dll")] + private static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle); } \ No newline at end of file diff --git a/WindowsEdgeLight/SettingsWindow.xaml.cs b/WindowsEdgeLight/SettingsWindow.xaml.cs index 74648b8..edcab9c 100644 --- a/WindowsEdgeLight/SettingsWindow.xaml.cs +++ b/WindowsEdgeLight/SettingsWindow.xaml.cs @@ -1,158 +1,158 @@ -using System.Windows; -using System.Windows.Controls; -using System.Windows.Interop; -using System.Windows.Media; - -namespace WindowsEdgeLight; - -public partial class SettingsWindow : Window -{ - private readonly MainWindow mainWindow; - private bool isInitializing = true; - - public SettingsWindow(MainWindow main) - { - InitializeComponent(); - mainWindow = main; - - BrightnessSlider.Value = mainWindow.GetBrightness(); - ColorTempSlider.Value = mainWindow.GetColorTemperature(); - ExcludeFromCaptureCheckBox.IsChecked = mainWindow.IsExcludeFromCaptureEnabled(); - ShowBrightnessCheckBox.IsChecked = mainWindow.GetIsBrightnessButtonsVisible(); - ShowColorTempCheckBox.IsChecked = mainWindow.GetIsColorTempButtonsVisible(); - ShowMonitorControlsCheckBox.IsChecked = mainWindow.GetIsControlMonitorsButtonVisible(); - ShowToggleCheckBox.IsChecked = mainWindow.GetIsToggleButtonVisible(); - - UpdateBrightnessLabel(); - UpdateColorTempLabel(); - - isInitializing = false; - } - - private void BrightnessSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) - { - if (isInitializing) return; - mainWindow.SetBrightness(e.NewValue, save: false); - UpdateBrightnessLabel(); - } - - private void BrightnessSlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) - { - mainWindow.SetBrightness(BrightnessSlider.Value, save: true); - } - - private void ColorTempSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) - { - if (isInitializing) return; - mainWindow.SetColorTemperature(e.NewValue, save: false); - UpdateColorTempLabel(); - } - - private void ColorTempSlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) - { - mainWindow.SetColorTemperature(ColorTempSlider.Value, save: true); - } - - private void SettingsWindow_Loaded(object sender, RoutedEventArgs e) - { - if (Owner == null) - { - return; - } - - const double gap = 12; - var ownerHandle = new WindowInteropHelper(Owner).Handle; - var screen = System.Windows.Forms.Screen.FromHandle(ownerHandle); - var transformFromDevice = PresentationSource.FromVisual(Owner)? - .CompositionTarget?.TransformFromDevice ?? Matrix.Identity; - var workArea = new Rect( - screen.WorkingArea.X * transformFromDevice.M11, - screen.WorkingArea.Y * transformFromDevice.M22, - screen.WorkingArea.Width * transformFromDevice.M11, - screen.WorkingArea.Height * transformFromDevice.M22); - - MaxHeight = Math.Max(200, workArea.Height - (gap * 2)); - var desiredLeft = Owner.Left + ((Owner.ActualWidth - ActualWidth) / 2); - Left = Math.Min(Math.Max(desiredLeft, workArea.Left + gap), workArea.Right - ActualWidth - gap); - - var aboveOwnerTop = Owner.Top - ActualHeight - gap; - if (aboveOwnerTop >= workArea.Top + gap) - { - Top = aboveOwnerTop; - return; - } - - var belowOwnerTop = Owner.Top + Owner.ActualHeight + gap; - if (belowOwnerTop + ActualHeight <= workArea.Bottom - gap) - { - Top = belowOwnerTop; - return; - } - - Top = workArea.Top + ((workArea.Height - ActualHeight) / 2); - } - - private void SettingsWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e) - { - mainWindow.SaveAppearanceSettings(); - } - - private void ExcludeFromCapture_Click(object sender, RoutedEventArgs e) - { - bool current = mainWindow.IsExcludeFromCaptureEnabled(); - bool desired = ExcludeFromCaptureCheckBox.IsChecked == true; - if (current != desired) - { - mainWindow.ToggleExcludeFromCapture(); - } - } - - private void UpdateBrightnessLabel() - { - if (BrightnessValueText != null) - BrightnessValueText.Text = $"{(int)(BrightnessSlider.Value * 100)}%"; - } - - private void UpdateColorTempLabel() - { - if (ColorTempValueText != null) - ColorTempValueText.Text = $"{(int)(ColorTempSlider.Value * 100)}%"; - } - - private void ShowToggle_Click(object sender, RoutedEventArgs e) - { - mainWindow.SetIsToggleVisible(ShowToggleCheckBox.IsChecked == true); - UpdateOwnerControlWindow(); - } - - private void ShowBrightness_Click(object sender, RoutedEventArgs e) - { - mainWindow.SetIsBrightnessButtonsVisible(ShowBrightnessCheckBox.IsChecked == true); - UpdateOwnerControlWindow(); - } - - private void ShowColorTemp_Click(object sender, RoutedEventArgs e) - { - mainWindow.SetIsColorTempButtonsVisible(ShowColorTempCheckBox.IsChecked == true); - UpdateOwnerControlWindow(); - } - - private void ShowMonitorControls_Click(object sender, RoutedEventArgs e) - { - mainWindow.SetIsControlMonitorsButtonVisible(ShowMonitorControlsCheckBox.IsChecked == true); - UpdateOwnerControlWindow(); - } - - private void ResetControlBarPosition_Click(object sender, RoutedEventArgs e) - { - mainWindow.ResetControlWindowPosition(); - } - - private void UpdateOwnerControlWindow() - { - if (Owner is ControlWindow controlWindow) - { - controlWindow.ApplyButtonVisibility(); - } - } -} +using System.Windows; +using System.Windows.Controls; +using System.Windows.Interop; +using System.Windows.Media; + +namespace WindowsEdgeLight; + +public partial class SettingsWindow : Window +{ + private readonly MainWindow mainWindow; + private bool isInitializing = true; + + public SettingsWindow(MainWindow main) + { + InitializeComponent(); + mainWindow = main; + + BrightnessSlider.Value = mainWindow.GetBrightness(); + ColorTempSlider.Value = mainWindow.GetColorTemperature(); + ExcludeFromCaptureCheckBox.IsChecked = mainWindow.IsExcludeFromCaptureEnabled(); + ShowBrightnessCheckBox.IsChecked = mainWindow.GetIsBrightnessButtonsVisible(); + ShowColorTempCheckBox.IsChecked = mainWindow.GetIsColorTempButtonsVisible(); + ShowMonitorControlsCheckBox.IsChecked = mainWindow.GetIsControlMonitorsButtonVisible(); + ShowToggleCheckBox.IsChecked = mainWindow.GetIsToggleButtonVisible(); + + UpdateBrightnessLabel(); + UpdateColorTempLabel(); + + isInitializing = false; + } + + private void BrightnessSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) + { + if (isInitializing) return; + mainWindow.SetBrightness(e.NewValue, save: false); + UpdateBrightnessLabel(); + } + + private void BrightnessSlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) + { + mainWindow.SetBrightness(BrightnessSlider.Value, save: true); + } + + private void ColorTempSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) + { + if (isInitializing) return; + mainWindow.SetColorTemperature(e.NewValue, save: false); + UpdateColorTempLabel(); + } + + private void ColorTempSlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) + { + mainWindow.SetColorTemperature(ColorTempSlider.Value, save: true); + } + + private void SettingsWindow_Loaded(object sender, RoutedEventArgs e) + { + if (Owner == null) + { + return; + } + + const double gap = 12; + var ownerHandle = new WindowInteropHelper(Owner).Handle; + var screen = System.Windows.Forms.Screen.FromHandle(ownerHandle); + var transformFromDevice = PresentationSource.FromVisual(Owner)? + .CompositionTarget?.TransformFromDevice ?? Matrix.Identity; + var workArea = new Rect( + screen.WorkingArea.X * transformFromDevice.M11, + screen.WorkingArea.Y * transformFromDevice.M22, + screen.WorkingArea.Width * transformFromDevice.M11, + screen.WorkingArea.Height * transformFromDevice.M22); + + MaxHeight = Math.Max(200, workArea.Height - (gap * 2)); + var desiredLeft = Owner.Left + ((Owner.ActualWidth - ActualWidth) / 2); + Left = Math.Min(Math.Max(desiredLeft, workArea.Left + gap), workArea.Right - ActualWidth - gap); + + var aboveOwnerTop = Owner.Top - ActualHeight - gap; + if (aboveOwnerTop >= workArea.Top + gap) + { + Top = aboveOwnerTop; + return; + } + + var belowOwnerTop = Owner.Top + Owner.ActualHeight + gap; + if (belowOwnerTop + ActualHeight <= workArea.Bottom - gap) + { + Top = belowOwnerTop; + return; + } + + Top = workArea.Top + ((workArea.Height - ActualHeight) / 2); + } + + private void SettingsWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e) + { + mainWindow.SaveAppearanceSettings(); + } + + private void ExcludeFromCapture_Click(object sender, RoutedEventArgs e) + { + bool current = mainWindow.IsExcludeFromCaptureEnabled(); + bool desired = ExcludeFromCaptureCheckBox.IsChecked == true; + if (current != desired) + { + mainWindow.ToggleExcludeFromCapture(); + } + } + + private void UpdateBrightnessLabel() + { + if (BrightnessValueText != null) + BrightnessValueText.Text = $"{(int)(BrightnessSlider.Value * 100)}%"; + } + + private void UpdateColorTempLabel() + { + if (ColorTempValueText != null) + ColorTempValueText.Text = $"{(int)(ColorTempSlider.Value * 100)}%"; + } + + private void ShowToggle_Click(object sender, RoutedEventArgs e) + { + mainWindow.SetIsToggleVisible(ShowToggleCheckBox.IsChecked == true); + UpdateOwnerControlWindow(); + } + + private void ShowBrightness_Click(object sender, RoutedEventArgs e) + { + mainWindow.SetIsBrightnessButtonsVisible(ShowBrightnessCheckBox.IsChecked == true); + UpdateOwnerControlWindow(); + } + + private void ShowColorTemp_Click(object sender, RoutedEventArgs e) + { + mainWindow.SetIsColorTempButtonsVisible(ShowColorTempCheckBox.IsChecked == true); + UpdateOwnerControlWindow(); + } + + private void ShowMonitorControls_Click(object sender, RoutedEventArgs e) + { + mainWindow.SetIsControlMonitorsButtonVisible(ShowMonitorControlsCheckBox.IsChecked == true); + UpdateOwnerControlWindow(); + } + + private void ResetControlBarPosition_Click(object sender, RoutedEventArgs e) + { + mainWindow.ResetControlWindowPosition(); + } + + private void UpdateOwnerControlWindow() + { + if (Owner is ControlWindow controlWindow) + { + controlWindow.ApplyButtonVisibility(); + } + } +}