diff --git a/Network Monitor.Tests/FullscreenHideManagerTests.cs b/Network Monitor.Tests/FullscreenHideManagerTests.cs new file mode 100644 index 0000000..25221ad --- /dev/null +++ b/Network Monitor.Tests/FullscreenHideManagerTests.cs @@ -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)); + } +} diff --git a/Network Monitor/App.config b/Network Monitor/App.config index 4a892fd..5fdf740 100644 --- a/Network Monitor/App.config +++ b/Network Monitor/App.config @@ -34,6 +34,9 @@ + + True + diff --git a/Network Monitor/FullscreenHideManager.cs b/Network Monitor/FullscreenHideManager.cs new file mode 100644 index 0000000..c98bfd4 --- /dev/null +++ b/Network Monitor/FullscreenHideManager.cs @@ -0,0 +1,166 @@ +using System; +using System.Runtime.InteropServices; +using System.Windows; +using Network_Monitor.Monitors; +using Network_Monitor.Properties; + +namespace Network_Monitor; + +/// +/// 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. +/// +/// +/// 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. +/// +public sealed class FullscreenHideManager : IDisposable +{ + private readonly Window _window; + private bool _isDisposed; + + /// + /// The fullscreen window the widget is hidden for, or while it's showing. + /// + private IntPtr _hiddenFor; + + /// + /// Hides for fullscreen apps while is on. + /// + public FullscreenHideManager(Window window) + { + _window = window; + Monitor.ClockTicked += Clock_Ticked; + } + + /// + /// Returns whether a window at fills , reaching every edge of it or past them, both in device pixels. + /// + public static bool FillsMonitor(Rect bounds, Rect monitor) => + bounds.Left <= monitor.Left && + bounds.Top <= monitor.Top && + bounds.Right >= monitor.Right && + bounds.Bottom >= monitor.Bottom; + + /// + /// 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. + /// + 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; + } + + /// + /// Checks on the window's thread, since the tick comes on a thread pool thread, which can't hide or show the window. + /// + 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); + } + + /// + /// Returns the fullscreen window the widget should be hidden for, or if it should be showing. + /// + 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; + } + + /// + /// Returns whether is an app's window that fills the monitor whose bounds are . + /// 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. + /// + private static bool IsFullscreen(IntPtr window, Rect screen) => + IsApp(window) && + !NativeMethods.IsZoomed(window) && + FillsMonitor(ScreenEdges.GetBounds(window), screen); + + /// + /// Returns whether 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. + /// + /// + /// 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. + /// + 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); + } +} diff --git a/Network Monitor/MainWindow.xaml b/Network Monitor/MainWindow.xaml index 1abb69e..d8bc83c 100644 --- a/Network Monitor/MainWindow.xaml +++ b/Network Monitor/MainWindow.xaml @@ -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" @@ -76,6 +77,10 @@ IsCheckable="True" IsChecked="{Binding Topmost, Source={x:Static p:Settings.Default}, Mode=TwoWay}" /> + + diff --git a/Network Monitor/MainWindow.xaml.cs b/Network Monitor/MainWindow.xaml.cs index 0c8e5bf..71e35b8 100644 --- a/Network Monitor/MainWindow.xaml.cs +++ b/Network Monitor/MainWindow.xaml.cs @@ -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) { @@ -110,10 +111,12 @@ private void ResizeByWheel(int delta) } /// - /// 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. /// public void Reveal() { + _fullscreenHideManager?.ShowNow(); + ScreenEdges.MoveTo(this, ScreenEdges.KeepOnScreen(ScreenEdges.GetBounds(this), ScreenEdges.GetScreenBounds(this))); Activate(); @@ -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) @@ -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(); } diff --git a/Network Monitor/Monitors/Monitor.cs b/Network Monitor/Monitors/Monitor.cs index 8c8526e..ac34169 100644 --- a/Network Monitor/Monitors/Monitor.cs +++ b/Network Monitor/Monitors/Monitor.cs @@ -48,6 +48,16 @@ protected Monitor(bool updatesEverySecond) }; } + /// + /// 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. + /// + public static event EventHandler ClockTicked + { + add => ClockTimer.SecondChanged += value; + remove => ClockTimer.SecondChanged -= value; + } + /// /// Name of the monitor. /// diff --git a/Network Monitor/Properties/Settings.Designer.cs b/Network Monitor/Properties/Settings.Designer.cs index 00958ce..878398d 100644 --- a/Network Monitor/Properties/Settings.Designer.cs +++ b/Network Monitor/Properties/Settings.Designer.cs @@ -148,5 +148,17 @@ public string InterfaceId { } } + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("True")] + public bool HideWhenFullscreen { + get { + return ((bool)(this["HideWhenFullscreen"])); + } + set { + this["HideWhenFullscreen"] = value; + } + } + } } diff --git a/Network Monitor/Properties/Settings.settings b/Network Monitor/Properties/Settings.settings index d38406e..48aec29 100644 --- a/Network Monitor/Properties/Settings.settings +++ b/Network Monitor/Properties/Settings.settings @@ -35,5 +35,8 @@ + + True + \ No newline at end of file diff --git a/Network Monitor/ScreenEdges.cs b/Network Monitor/ScreenEdges.cs index 8d729b3..681cf43 100644 --- a/Network Monitor/ScreenEdges.cs +++ b/Network Monitor/ScreenEdges.cs @@ -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 and can lag behind a position restored straight onto the window. /// - public static Rect GetBounds(Window window) + public static Rect GetBounds(Window window) => GetBounds(new WindowInteropHelper(window).Handle); + + /// + /// Returns where the window with , such as another app's, is on screen, in device pixels. + /// + public static Rect GetBounds(IntPtr handle) { - NativeMethods.GetWindowRect(new WindowInteropHelper(window).Handle, out var rect); + NativeMethods.GetWindowRect(handle, out var rect); return ToRect(rect); } @@ -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. /// - public static Rect GetScreenBounds(Window window) + public static Rect GetScreenBounds(Window window) => GetScreenBounds(new WindowInteropHelper(window).Handle); + + /// + /// Returns the bounds of the monitor the window with , such as another app's, is on (or nearest to), in device pixels. + /// + 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)) }; diff --git a/README.md b/README.md index 7494b4f..c66c8eb 100644 --- a/README.md +++ b/README.md @@ -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.