Skip to content

Commit f1af23c

Browse files
committed
refactor: sub-window's startup location (#2100)
Child window will use current actived window (fall back to `MainWindow`) to calculate the startup location (likes `CenterScreen` mode). The benefits of doing this are: - Solve the problem that newly opened windows always appear on the primary screen in multi-screen situations. - Newly opened windows always display on the currently used screen. This reduces the need for users to move the mouse. Signed-off-by: leo <longshuang@msn.cn>
1 parent 2cde927 commit f1af23c

File tree

1 file changed

+42
-8
lines changed

1 file changed

+42
-8
lines changed

src/App.axaml.cs

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -148,18 +148,52 @@ public static Task ShowDialog(object data, Window owner = null)
148148

149149
public static void ShowWindow(object data)
150150
{
151-
if (data is Views.ChromelessWindow window)
151+
if (data is not Views.ChromelessWindow window)
152152
{
153-
window.Show();
154-
return;
155-
}
153+
window = CreateViewForViewModel(data) as Views.ChromelessWindow;
154+
if (window == null)
155+
return;
156156

157-
window = CreateViewForViewModel(data) as Views.ChromelessWindow;
158-
if (window != null)
159-
{
160157
window.DataContext = data;
161-
window.Show();
162158
}
159+
160+
do
161+
{
162+
if (Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime { Windows: { Count: > 0 } windows })
163+
{
164+
// Try to find the actived window (fall back to `MainWindow`)
165+
Window actived = windows[0];
166+
if (!actived.IsActive)
167+
{
168+
for (var i = 1; i < windows.Count; i++)
169+
{
170+
var test = windows[i];
171+
if (test.IsActive)
172+
{
173+
actived = test;
174+
break;
175+
}
176+
}
177+
}
178+
179+
// Get the screen where current window locates.
180+
var screen = actived.Screens.ScreenFromWindow(actived) ?? actived.Screens.Primary;
181+
if (screen == null)
182+
break;
183+
184+
// Calculate the startup position (Center Screen Mode) of target window
185+
var rect = new PixelRect(PixelSize.FromSize(window.ClientSize, actived.DesktopScaling));
186+
var centeredRect = screen.WorkingArea.CenterRect(rect);
187+
if (actived.Screens.ScreenFromPoint(centeredRect.Position) == null)
188+
break;
189+
190+
// Use the startup position
191+
window.WindowStartupLocation = WindowStartupLocation.Manual;
192+
window.Position = centeredRect.Position;
193+
}
194+
} while (false);
195+
196+
window.Show();
163197
}
164198

165199
public static async Task<bool> AskConfirmAsync(string message, Models.ConfirmButtonType buttonType = Models.ConfirmButtonType.OkCancel)

0 commit comments

Comments
 (0)