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
19 changes: 19 additions & 0 deletions Network Monitor.Tests/FullscreenHideManagerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System.Windows;

namespace Network_Monitor.Tests;

public class FullscreenHideManagerTests
{
private static readonly Rect Screen = new(0, 0, 2560, 1440);

[Theory]
[InlineData(0, 0, 2560, 1440, true)] // The size of the monitor.
[InlineData(-8, -31, 2576, 1479, true)] // Past every edge, like a game that pushes its title bar off the top of the screen.
[InlineData(1, 0, 2559, 1440, false)] // A pixel short of the left.
[InlineData(0, 0, 2560, 1392, false)] // Maximized above a taskbar.
[InlineData(2560, 0, 1920, 1080, false)] // Fullscreen on another monitor.
public void FillsMonitor_OnlyWhenItReachesEveryEdge(double left, double top, double width, double height, bool expected)
{
Assert.Equal(expected, FullscreenHideManager.FillsMonitor(new Rect(left, top, width, height), Screen));
}
}
3 changes: 3 additions & 0 deletions Network Monitor/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
<setting name="InterfaceId" serializeAs="String">
<value />
</setting>
<setting name="HideWhenFullscreen" serializeAs="String">
<value>True</value>
</setting>
</Network_Monitor.Properties.Settings>
</userSettings>
<applicationSettings>
Expand Down
166 changes: 166 additions & 0 deletions Network Monitor/FullscreenHideManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
using System;
using System.Runtime.InteropServices;
using System.Windows;
using Network_Monitor.Monitors;
using Network_Monitor.Properties;

namespace Network_Monitor;

/// <summary>
/// Hides the widget while a fullscreen app, like a game, a video, or a slideshow, is in front on the monitor it's on, and shows it again when that ends, as DesktopClock does.
/// </summary>
/// <remarks>
/// It checks on the readings' one-second tick rather than on a timer of its own, so a fullscreen app is caught within a second.
/// The setting is read on each tick too, so turning it off brings the widget back by the next one.
/// </remarks>
public sealed class FullscreenHideManager : IDisposable
{
private readonly Window _window;
private bool _isDisposed;

/// <summary>
/// The fullscreen window the widget is hidden for, or <see cref="IntPtr.Zero" /> while it's showing.
/// </summary>
private IntPtr _hiddenFor;

/// <summary>
/// Hides <paramref name="window" /> for fullscreen apps while <see cref="Settings.HideWhenFullscreen" /> is on.
/// </summary>
public FullscreenHideManager(Window window)
{
_window = window;
Monitor.ClockTicked += Clock_Ticked;
}

/// <summary>
/// Returns whether a window at <paramref name="bounds" /> fills <paramref name="monitor" />, reaching every edge of it or past them, both in device pixels.
/// </summary>
public static bool FillsMonitor(Rect bounds, Rect monitor) =>
bounds.Left <= monitor.Left &&
bounds.Top <= monitor.Top &&
bounds.Right >= monitor.Right &&
bounds.Bottom >= monitor.Bottom;

/// <summary>
/// Shows the widget if it's hidden, such as when it's asked to come into view.
/// It stays in front of the fullscreen app until that's brought to the front again.
/// </summary>
public void ShowNow()
{
// It can be asked just after the window has closed, such as while Windows signs out, and a closed window can't be shown again.
if (!_isDisposed)
Show();
}

public void Dispose()
{
_isDisposed = true;
Monitor.ClockTicked -= Clock_Ticked;
}

/// <summary>
/// Checks on the window's thread, since the tick comes on a thread pool thread, which can't hide or show the window.
/// </summary>
private void Clock_Ticked(object sender, EventArgs e) => _window.Dispatcher.BeginInvoke(new Action(Update));

private void Update()
{
if (_isDisposed)
return;

var hiddenFor = Settings.Default.HideWhenFullscreen ? FindWindowToHideFor() : IntPtr.Zero;

if (hiddenFor == IntPtr.Zero)
Show();
else
Hide(hiddenFor);
}

/// <summary>
/// Returns the fullscreen window the widget should be hidden for, or <see cref="IntPtr.Zero" /> if it should be showing.
/// </summary>
private IntPtr FindWindowToHideFor()
{
var screen = ScreenEdges.GetScreenBounds(_window);
var front = NativeMethods.GetForegroundWindow();

if (IsFullscreen(front, screen))
return front;

// Any other app's window in front on the widget's monitor brings it back.
if (IsApp(front) && ScreenEdges.GetScreenBounds(front) == screen)
return IntPtr.Zero;

// Otherwise, like with the desktop or a window on another monitor in front, it stays hidden while the window it's hidden for still fills its monitor, so a video left fullscreen beside the window being worked in isn't covered.
return _hiddenFor != IntPtr.Zero && IsFullscreen(_hiddenFor, screen) ? _hiddenFor : IntPtr.Zero;
}

/// <summary>
/// Returns whether <paramref name="window" /> is an app's window that fills the monitor whose bounds are <paramref name="screen" />.
/// A maximized window doesn't count, though on a monitor without a taskbar, or with one that hides itself, its borders reach past every edge too.
/// </summary>
private static bool IsFullscreen(IntPtr window, Rect screen) =>
IsApp(window) &&
!NativeMethods.IsZoomed(window) &&
FillsMonitor(ScreenEdges.GetBounds(window), screen);

/// <summary>
/// Returns whether <paramref name="window" /> is an app's window that can be seen.
/// That leaves out the shell's windows, like the desktop that fills the monitor after Win+D, the taskbar, and Alt+Tab.
/// </summary>
/// <remarks>
/// The shell's windows are told apart by their process rather than their names, which have changed from one version of Windows to the next.
/// </remarks>
private static bool IsApp(IntPtr window)
{
if (!NativeMethods.IsWindowVisible(window))
return false;

NativeMethods.GetWindowThreadProcessId(window, out var processId);
NativeMethods.GetWindowThreadProcessId(NativeMethods.GetShellWindow(), out var shellProcessId);

return processId != shellProcessId;
}

private void Hide(IntPtr fullscreenWindow)
{
if (_hiddenFor == IntPtr.Zero)
{
// A reading's tooltip is a window of its own, which could otherwise stay open over the fullscreen app for up to a minute.
MonitorView.CloseToolTip();
_window.Hide();
}

// It can go straight from one fullscreen app to another, like from a video to a game, and stays hidden for whichever is in front.
_hiddenFor = fullscreenWindow;
}

private void Show()
{
if (_hiddenFor == IntPtr.Zero)
return;

_hiddenFor = IntPtr.Zero;

// It comes back where it was without taking the focus, as ShowActivated is off, so whatever's in front, like the app that just left fullscreen, keeps the keyboard.
_window.Show();
}

private static class NativeMethods
{
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
public static extern IntPtr GetShellWindow();

[DllImport("user32.dll")]
public static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint processId);

[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hwnd);

[DllImport("user32.dll")]
public static extern bool IsZoomed(IntPtr hwnd);
}
}
5 changes: 5 additions & 0 deletions Network Monitor/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
Title="Network Monitor"
Topmost="{Binding Topmost, Source={x:Static p:Settings.Default}, Mode=TwoWay}"
ShowInTaskbar="{Binding ShowInTaskbar, Source={x:Static p:Settings.Default}, Mode=TwoWay}"
ShowActivated="False"
SizeToContent="WidthAndHeight"
ResizeMode="NoResize"
WindowStyle="None"
Expand Down Expand Up @@ -76,6 +77,10 @@
IsCheckable="True"
IsChecked="{Binding Topmost, Source={x:Static p:Settings.Default}, Mode=TwoWay}" />

<MenuItem Header="Hi_de when fullscreen"
IsCheckable="True"
IsChecked="{Binding HideWhenFullscreen, Source={x:Static p:Settings.Default}, Mode=TwoWay}" />

<MenuItem Header="_Show in taskbar"
IsCheckable="True"
IsChecked="{Binding ShowInTaskbar, Source={x:Static p:Settings.Default}, Mode=TwoWay}" />
Expand Down
11 changes: 10 additions & 1 deletion Network Monitor/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ private void MainWindow_OnMouseDown(object sender, MouseButtonEventArgs e)
private bool _isBeingMoved;
private ScreenEdges.FixedEdges? _fixedEdges;
private bool _isRepositioning;
private FullscreenHideManager _fullscreenHideManager;

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
Expand Down Expand Up @@ -110,10 +111,12 @@ private void ResizeByWheel(int delta)
}

/// <summary>
/// Brings the widget into view when its exe is started again: in front of other windows, and fully back on a screen if it was partly off one.
/// Brings the widget into view when its exe is started again: in front of other windows, even a fullscreen app it's hidden for, and fully back on a screen if it was partly off one.
/// </summary>
public void Reveal()
{
_fullscreenHideManager?.ShowNow();

ScreenEdges.MoveTo(this, ScreenEdges.KeepOnScreen(ScreenEdges.GetBounds(this), ScreenEdges.GetScreenBounds(this)));

Activate();
Expand Down Expand Up @@ -258,6 +261,9 @@ private void Window_SourceInitialized(object sender, EventArgs e)
{
// System.Configuration doesn't like the WindowPlacement struct sometimes.
}

// Started once the window has a handle and has been put back on its monitor, which is the one that's watched.
_fullscreenHideManager = new FullscreenHideManager(this);
}

private void Window_LocationChanged(object sender, EventArgs e)
Expand All @@ -274,6 +280,9 @@ private void Window_LocationChanged(object sender, EventArgs e)

private void Window_Closing(object sender, CancelEventArgs e)
{
// Nothing should hide or show the widget while it closes.
_fullscreenHideManager?.Dispose();

Settings.Default.Placement = WindowPlacementFunctions.GetPlacement(this);
SettingsSaver.SaveNow();
}
Expand Down
10 changes: 10 additions & 0 deletions Network Monitor/Monitors/Monitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ protected Monitor(bool updatesEverySecond)
};
}

/// <summary>
/// Occurs on each tick of the clock that updates the monitors, on a thread pool thread.
/// Anything else that's checked once a second can keep in step with them this way, rather than wake the app at moments of its own.
/// </summary>
public static event EventHandler ClockTicked
{
add => ClockTimer.SecondChanged += value;
remove => ClockTimer.SecondChanged -= value;
}

/// <summary>
/// Name of the monitor.
/// </summary>
Expand Down
12 changes: 12 additions & 0 deletions Network Monitor/Properties/Settings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Network Monitor/Properties/Settings.settings
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,8 @@
<Setting Name="InterfaceId" Type="System.String" Scope="User">
<Value Profile="(Default)" />
</Setting>
<Setting Name="HideWhenFullscreen" Type="System.Boolean" Scope="User">
<Value Profile="(Default)">True</Value>
</Setting>
</Settings>
</SettingsFile>
17 changes: 13 additions & 4 deletions Network Monitor/ScreenEdges.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,14 @@ public static Size ToDevicePixels(Size size, DpiScale dpi) =>
/// 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 Rect GetBounds(Window window)
public static Rect GetBounds(Window window) => GetBounds(new WindowInteropHelper(window).Handle);

/// <summary>
/// Returns where the window with <paramref name="handle" />, such as another app's, is on screen, in device pixels.
/// </summary>
public static Rect GetBounds(IntPtr handle)
{
NativeMethods.GetWindowRect(new WindowInteropHelper(window).Handle, out var rect);
NativeMethods.GetWindowRect(handle, out var rect);
return ToRect(rect);
}

Expand All @@ -101,9 +106,13 @@ public static void MoveTo(Window window, Point position) =>
/// 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)
public static Rect GetScreenBounds(Window window) => GetScreenBounds(new WindowInteropHelper(window).Handle);

/// <summary>
/// Returns the bounds of the monitor the window with <paramref name="handle" />, such as another app's, is on (or nearest to), in device pixels.
/// </summary>
public static Rect GetScreenBounds(IntPtr handle)
{
var handle = new WindowInteropHelper(window).Handle;
var monitor = NativeMethods.MonitorFromWindow(handle, NativeMethods.MONITOR_DEFAULTTONEAREST);
var info = new NativeMethods.MONITORINFO { cbSize = Marshal.SizeOf(typeof(NativeMethods.MONITORINFO)) };

Expand Down
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.
- **Hides for fullscreen apps:** steps aside while a game, video, or slideshow fills its monitor (on by default).
- **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.
Expand Down