CenterScreen.axaml代码
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Width="400" Height="250" x:Class="AvaloniaUI.CenterScreen" Title="CenterScreen"> <StackPanel Margin="10" HorizontalAlignment="Center" VerticalAlignment="Center"> <Button Name="cmdCenter" Content="Center" Click="cmdCenter_Click"/> </StackPanel> </Window>
CenterScreen.axaml.cs代码
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
namespace AvaloniaUI;
public partial class CenterScreen : Window
{
public CenterScreen()
{
InitializeComponent();
}
private void cmdCenter_Click(object? sender, RoutedEventArgs e)
{
var screen = Screens.ScreenFromWindow(this) ?? Screens.Primary;
if (screen is null)
return;
// 工作区(排除任务栏等)
var workArea = screen.WorkingArea;
// 当前窗口大小(像素)
var windowWidth = (int)Bounds.Width;
var windowHeight = (int)Bounds.Height;
var x = workArea.X + (workArea.Width - windowWidth) / 2;
var y = workArea.Y + (workArea.Height - windowHeight) / 2;
Position = new PixelPoint(x, y);
}
}
运行效果

浙公网安备 33010602011771号