Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Network Monitor.Tests/SizeAndPlacementTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,15 @@ public void KeepOnScreen_PullsAWindowBackOntoTheScreen()
Assert.Equal(new Point(2432, 0), ScreenEdges.KeepOnScreen(new Rect(2500, -20, 128, 138), Screen));
}

[Fact]
public void ToDevicePixels_AtAScaleThatDoesNotDivideEvenly_GivesWholePixels()
{
// At 175%, 115 pixels is about 65.71 units, which multiplies back to 114.99999999999999.
var size = ScreenEdges.ToDevicePixels(new Size(115 / 1.75, 122 / 1.75), new DpiScale(1.75, 1.75));

Assert.Equal(new Size(115, 122), size);
}

private static Point Resize(Rect oldBounds, Size newSize) =>
ScreenEdges.GetPositionAfterResize(oldBounds, newSize, Screen, ScreenEdges.GetFixedEdges(oldBounds, Screen));
}
4 changes: 4 additions & 0 deletions Network Monitor/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ protected override void OnStartup(StartupEventArgs e)
// Three numbers gain nothing from the graphics card, and drawing them in software saves about 10 MB of memory with no visible difference.
RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;

// app.manifest has Windows leave each monitor's scale to the app, and this has WPF draw the widget again at the new scale when it changes, rather than keep the old one.
// It has to be set before the first window is created.
AppContext.SetSwitch("Switch.System.Windows.DoNotScaleForDpiChanges", false);

base.OnStartup(e);

if (!SingleInstance.TryClaim(ExePath))
Expand Down
29 changes: 19 additions & 10 deletions Network Monitor/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using Network_Monitor.Monitors;
using Network_Monitor.Properties;
using WpfWindowPlacement;
Expand Down Expand Up @@ -52,10 +53,13 @@ private void MainWindow_OnMouseDown(object sender, MouseButtonEventArgs e)
}

private const int WM_MOUSEWHEEL = 0x020A;
private const int WM_ENTERSIZEMOVE = 0x0231;
private const int WM_EXITSIZEMOVE = 0x0232;
private const int MK_CONTROL = 0x0008;

private double _pendingWheelSteps;
private bool _hasRendered;
private bool _isBeingMoved;
private ScreenEdges.FixedEdges? _fixedEdges;
private bool _isRepositioning;

Expand All @@ -69,13 +73,19 @@ private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref b
var point = lParam.ToInt64();

// Windows can send the wheel to the active window wherever the pointer is, so only resize when it's over the widget.
if ((data & MK_CONTROL) != 0 && ScreenEdges.IsOverWindow(this, (short)(point & 0xFFFF), (short)((point >> 16) & 0xFFFF)))
if ((data & MK_CONTROL) != 0 && ScreenEdges.GetBounds(this).Contains((short)(point & 0xFFFF), (short)((point >> 16) & 0xFFFF)))
{
ResizeByWheel((short)((data >> 16) & 0xFFFF));
handled = true;
}
}

// While the window is dragged, or moved with the keyboard, Windows moves it along with the pointer, and nothing else should move it.
if (msg == WM_ENTERSIZEMOVE)
_isBeingMoved = true;
else if (msg == WM_EXITSIZEMOVE)
_isBeingMoved = false;

return IntPtr.Zero;
}

Expand Down Expand Up @@ -104,11 +114,8 @@ private void ResizeByWheel(int delta)
/// </summary>
public void Reveal()
{
var bounds = new Rect(ScreenEdges.GetTopLeft(this), new Size(ActualWidth, ActualHeight));
var position = ScreenEdges.KeepOnScreen(bounds, ScreenEdges.GetScreenBounds(this));
ScreenEdges.MoveTo(this, ScreenEdges.KeepOnScreen(ScreenEdges.GetBounds(this), ScreenEdges.GetScreenBounds(this)));

Left = position.X;
Top = position.Y;
Activate();
}

Expand All @@ -120,19 +127,21 @@ private void Window_ContentRendered(object sender, EventArgs e)
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
// Sizing while the window first appears isn't a resize, and moving it then would undo its restored position.
if (!_hasRendered || e.PreviousSize.Width <= 0 || e.PreviousSize.Height <= 0)
// Nor is the small change in size when it's dragged onto a monitor with a different scale, when it should stay under the pointer.
if (!_hasRendered || _isBeingMoved || e.PreviousSize.Width <= 0 || e.PreviousSize.Height <= 0)
return;

var oldBounds = new Rect(ScreenEdges.GetTopLeft(this), e.PreviousSize);
// The sizes are in WPF units, so they're measured in device pixels like the screen, at the window's scale now.
var dpi = VisualTreeHelper.GetDpi(this);
var oldBounds = new Rect(ScreenEdges.GetBounds(this).TopLeft, ScreenEdges.ToDevicePixels(e.PreviousSize, dpi));
var screen = ScreenEdges.GetScreenBounds(this);
_fixedEdges ??= ScreenEdges.GetFixedEdges(oldBounds, screen);
var position = ScreenEdges.GetPositionAfterResize(oldBounds, e.NewSize, screen, _fixedEdges.Value);
var position = ScreenEdges.GetPositionAfterResize(oldBounds, ScreenEdges.ToDevicePixels(e.NewSize, dpi), screen, _fixedEdges.Value);

_isRepositioning = true;
try
{
Left = position.X;
Top = position.Y;
ScreenEdges.MoveTo(this, position);
}
finally
{
Expand Down
1 change: 1 addition & 0 deletions Network Monitor/Network Monitor.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<UseWPF>true</UseWPF>
<LangVersion>latest</LangVersion>
<ApplicationIcon>Network Monitor.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<Copyright>© Daniel Chalmers</Copyright>
<Version>0.0.0</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
Expand Down
59 changes: 36 additions & 23 deletions Network Monitor/ScreenEdges.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;

namespace Network_Monitor;

/// <summary>
/// Keeps the widget against the screen edges it's parked near when its size changes, and on its monitor.
/// Windows grow from their top-left corner, so a widget parked in a bottom or right corner would otherwise spill off the screen whenever it got bigger.
/// </summary>
/// <remarks>
/// Places on the screen are in device pixels, as Windows gives them, rather than in WPF's units.
/// Each monitor can have its own scale, and a window's <see cref="Window.Left" /> and <see cref="Window.Top" /> are in the units of whichever monitor it's on at the time, so they don't line up from one monitor to the next.
/// </remarks>
public static class ScreenEdges
{
/// <summary>
Expand Down Expand Up @@ -64,28 +67,38 @@ public static Point KeepOnScreen(Rect bounds, Rect screen)
}

/// <summary>
/// Returns where the window actually is on screen, in the window's own units.
/// Returns how big <paramref name="size" />, in WPF units, is in device pixels at the scale <paramref name="dpi" />.
/// It's rounded to whole pixels, which is all a window can measure.
/// </summary>
public static Size ToDevicePixels(Size size, DpiScale dpi) =>
new(Math.Round(size.Width * dpi.DpiScaleX), Math.Round(size.Height * dpi.DpiScaleY));

/// <summary>
/// Returns where the window actually is on screen, in device pixels.
/// This is read from the window itself because <see cref="Window.Left" /> and <see cref="Window.Top" /> can lag behind a position restored straight onto the window.
/// </summary>
public static Point GetTopLeft(Window window)
public static Rect GetBounds(Window window)
{
NativeMethods.GetWindowRect(new WindowInteropHelper(window).Handle, out var rect);
return GetFromDevice(window).Transform(new Point(rect.Left, rect.Top));
return ToRect(rect);
}

/// <summary>
/// Returns whether a point on the screen, in device pixels, is over the window.
/// Moves the window's top-left corner to <paramref name="position" />, in device pixels, without resizing or activating it.
/// It's moved in one step, because setting <see cref="Window.Left" /> and then <see cref="Window.Top" /> could take it across another monitor on the way and change its scale partway.
/// </summary>
public static bool IsOverWindow(Window window, int x, int y)
{
if (!NativeMethods.GetWindowRect(new WindowInteropHelper(window).Handle, out var rect))
return false;

return x >= rect.Left && x < rect.Right && y >= rect.Top && y < rect.Bottom;
}
public static void MoveTo(Window window, Point position) =>
NativeMethods.SetWindowPos(
new WindowInteropHelper(window).Handle,
IntPtr.Zero,
(int)Math.Round(position.X),
(int)Math.Round(position.Y),
0,
0,
NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE);

/// <summary>
/// Returns the bounds of the monitor the window is on (or nearest to), in the window's own units.
/// Returns the bounds of the monitor the window is on (or nearest to), in device pixels.
/// The whole monitor is used rather than the area above the taskbar, so a widget parked on the taskbar can stay there.
/// </summary>
public static Rect GetScreenBounds(Window window)
Expand All @@ -94,22 +107,19 @@ public static Rect GetScreenBounds(Window window)
var monitor = NativeMethods.MonitorFromWindow(handle, NativeMethods.MONITOR_DEFAULTTONEAREST);
var info = new NativeMethods.MONITORINFO { cbSize = Marshal.SizeOf(typeof(NativeMethods.MONITORINFO)) };

if (!NativeMethods.GetMonitorInfo(monitor, ref info))
return SystemParameters.WorkArea;

var fromDevice = GetFromDevice(window);
var topLeft = fromDevice.Transform(new Point(info.rcMonitor.Left, info.rcMonitor.Top));
var bottomRight = fromDevice.Transform(new Point(info.rcMonitor.Right, info.rcMonitor.Bottom));

return new Rect(topLeft, bottomRight);
NativeMethods.GetMonitorInfo(monitor, ref info);
return ToRect(info.rcMonitor);
}

private static Matrix GetFromDevice(Window window) =>
PresentationSource.FromVisual(window)?.CompositionTarget?.TransformFromDevice ?? Matrix.Identity;
private static Rect ToRect(NativeMethods.RECT rect) =>
new(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);

private static class NativeMethods
{
public const uint MONITOR_DEFAULTTONEAREST = 2;
public const uint SWP_NOSIZE = 0x0001;
public const uint SWP_NOZORDER = 0x0004;
public const uint SWP_NOACTIVATE = 0x0010;

[StructLayout(LayoutKind.Sequential)]
public struct RECT
Expand All @@ -134,5 +144,8 @@ public struct MONITORINFO

[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hwnd, out RECT rect);

[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hwnd, IntPtr insertAfter, int x, int y, int cx, int cy, uint flags);
}
}
27 changes: 27 additions & 0 deletions Network Monitor/app.manifest
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<!--The same identity and execution level the compiler gave the app before it had a manifest of its own-->
<assemblyIdentity version="1.0.0.0" name="MyApplication.app" />

<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>

<!--Windows 10 and 11. WPF only draws at each monitor's own scale on Windows 10 and later, and without this, Windows can tell the app it's running on Windows 8-->
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>

<!--Draws the widget at each monitor's own scale, so it stays sharp on all of them instead of Windows stretching what was drawn for the main monitor-->
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings>
</application>
</assembly>
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ Hover for a 60-second sparkline and the stats behind it: min/avg/max, jitter, pa
- **Light, dark, or auto:** pick a theme, or let Auto follow the Windows light/dark mode and accent color.
- **Resize instantly:** drag the size slider, or hold **Ctrl** and scroll over the widget to scale it.
- **Stays where you want:** keep it on top of other windows, drag it anywhere, and it remembers where you left it.
- **Sharp on every monitor:** stays crisp on monitors with different scaling, like a laptop beside a monitor.
- **Copy on demand:** double-click, or right-click → **Copy**, to grab the current numbers.
- **Starts with Windows:** optionally launch on sign-in, and check for updates in one click from the menu.
- **Honest outages:** when pings stop, a clock counts the time since the last reply; hover for when it started.
Expand Down