WPF 全屏顯示實現(無標題欄按鈕 + 自定義退出按鈕)
完整實現代碼
MainWindow.xaml
<Window x:Class="FullScreenApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="全屏應用" WindowState="Maximized" WindowStyle="None"ResizeMode="NoResize" Background="Black"><Grid><!-- 主內容區域 --><TextBlock Text="全屏應用演示" HorizontalAlignment="Center" VerticalAlignment="Center"Foreground="White" FontSize="36"/><!-- 自定義退出按鈕 --><Button x:Name="ExitButton" Content="退出程序" Width="100" Height="40"HorizontalAlignment="Right" VerticalAlignment="Bottom"Margin="20"Click="ExitButton_Click"/></Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;namespace FullScreenApp
{public partial class MainWindow : Window{public MainWindow(){InitializeComponent();// 確保窗口全屏this.WindowState = WindowState.Maximized;this.WindowStyle = WindowStyle.None;// 可選:防止其他窗口覆蓋this.Topmost = true;}private void ExitButton_Click(object sender, RoutedEventArgs e){// 退出應用程序Application.Current.Shutdown();}// 可選:響應ESC鍵退出protected override void OnKeyDown(KeyEventArgs e){if (e.Key == Key.Escape){Application.Current.Shutdown();}base.OnKeyDown(e);}}
}
進階功能
1. 添加淡入淡出動畫效果
<Window.Resources><Storyboard x:Key="FadeOut"><DoubleAnimation Storyboard.TargetProperty="Opacity"From="1" To="0" Duration="0:0:0.3"/></Storyboard>
</Window.Resources>
然后在退出按鈕點擊事件中:
private async void ExitButton_Click(object sender, RoutedEventArgs e)
{var storyboard = (Storyboard)FindResource("FadeOut");storyboard.Begin(this);await Task.Delay(300); // 等待動畫完成Application.Current.Shutdown();
}
2. 防止誤操作退出(添加確認對話框)
private void ExitButton_Click(object sender, RoutedEventArgs e)
{var result = MessageBox.Show("確定要退出程序嗎?", "確認退出", MessageBoxButton.YesNo, MessageBoxImage.Question);if (result == MessageBoxResult.Yes){Application.Current.Shutdown();}
}
3. 多顯示器支持(在主顯示器全屏)
public MainWindow()
{InitializeComponent();// 獲取主顯示器信息var screen = System.Windows.Forms.Screen.PrimaryScreen;// 設置窗口位置和大小this.Left = screen.Bounds.Left;this.Top = screen.Bounds.Top;this.Width = screen.Bounds.Width;this.Height = screen.Bounds.Height;this.WindowStyle = WindowStyle.None;this.WindowState = WindowState.Normal; // 必須設置為Normal才能自定義大小
}
注意事項
- 窗口樣式:
WindowStyle="None"
會移除所有窗口裝飾,包括標題欄和邊框 - 調整大小:
ResizeMode="NoResize"
防止用戶調整窗口大小 - 任務欄:全屏窗口默認會覆蓋任務欄,如需顯示任務欄,請調整窗口大小
- 快捷鍵:添加ESC鍵退出功能可以提升用戶體驗
- 性能:全屏應用通常需要優化渲染性能,特別是包含動畫或視頻時