Skip to content

Commit

Permalink
(#520) Center window on monitor when it goes out of bounds
Browse files Browse the repository at this point in the history
  • Loading branch information
jibedoubleve committed Jul 30, 2024
1 parent 34121e2 commit 541357a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
27 changes: 24 additions & 3 deletions src/Lanceur.Infra.Win32/Utils/ScreenRuler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ public static class ScreenRuler

#region Methods

public static Coordinate GetCenterCoordinate(double topOffset = double.MaxValue)
private static Coordinate GetCenterCoordinate(double topOffset)
{
var screenWidth = SystemParameters.PrimaryScreenWidth;
var screenHeight = SystemParameters.PrimaryScreenHeight;

var x = (screenWidth - WindowWidth) / 2;
var y = topOffset == double.MaxValue
var y = topOffset >= double.MaxValue
? (screenHeight - WindowHeight) / 2
: topOffset;

Expand All @@ -43,12 +43,33 @@ public static Coordinate SetDefaultPosition()
public static void SetWindowPosition(Coordinate coordinate)
{
var win = Application.Current.MainWindow;

if (win is null) return;

win.Left = coordinate.X;
win.Top = coordinate.Y;
}


public static bool IsWindowOutOfScreen()
{
var win = Application.Current.MainWindow;
if (win is null) return true;

// Obtain the dimensions of the primary screen
var workArea = SystemParameters.WorkArea;

// Obtain the dimensions and position of the window
var winLeft = win.Left;
var winTop = win.Top;
var winWidth = winLeft + win.Width;
var winHeight = winTop + win.Height;

// Check if the window is completely or partially off the screen
return winLeft < workArea.Left ||
winTop < workArea.Top ||
winWidth > workArea.Right ||
winHeight > workArea.Bottom;
}

#endregion Methods
}
Expand Down
16 changes: 10 additions & 6 deletions src/Lanceur/Views/MainView.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -241,17 +241,21 @@ private void OnTextChanged(object sender, TextChangedEventArgs e)

private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
//TODO value from settings
var stg = _settings.Current;
var hk = stg.HotKey;
var settings = _settings.Current;
var hk = settings.HotKey;
SetShortcut((Key)hk.Key, (ModifierKeys)hk.ModifierKey);

//var coordinate = ScreenRuler.GetCenterCoordinate(ScreenRuler.DefaultTopOffset);
var coordinate = new Coordinate(stg.Window.Position.Left, stg.Window.Position.Top);

var coordinate = new Coordinate(settings.Window.Position.Left, settings.Window.Position.Top);

if (coordinate.IsEmpty) ScreenRuler.SetDefaultPosition();
else ScreenRuler.SetWindowPosition(coordinate);

if (ScreenRuler.IsWindowOutOfScreen())
{
_logger.LogInformation("Window is out of screen. Set it to default position at centre of the screen");
ScreenRuler.SetDefaultPosition();
}

ShowWindow();
}

Expand Down

0 comments on commit 541357a

Please sign in to comment.