WinForm 真正的全螢幕需:隱藏工作列、移除表單邊框、最大化視窗、處理多螢幕、支援 F11/ESC 切換。本文提供可直接使用的 `FullScreenForm` 基底類別。
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class FullScreenForm : Form
{
private bool _isFullScreen;
private Rectangle _oldBounds;
private int _taskbarHwnd;
#region Win32 API
[DllImport("user32.dll")] private static extern int FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")] private static extern int ShowWindow(int hwnd, int nCmdShow);
[DllImport("user32.dll")] private static extern int SystemParametersInfo(int uAction, int uParam, ref Rectangle lpvParam, int fuWinIni);
private const int SW_HIDE = 0;
private const int SW_SHOW = 5;
private const int SPI_GETWORKAREA = 0x0030;
private const int SPI_SETWORKAREA = 0x002F;
private const int SPIF_UPDATEINIFILE = 0x01;
#endregion
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_taskbarHwnd = FindWindow("Shell_TrayWnd", null);
KeyPreview = true; // 讓表單接收鍵盤事件
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.KeyCode == Keys.F11) ToggleFullScreen();
else if (e.KeyCode == Keys.Escape && _isFullScreen) ToggleFullScreen();
}
public void ToggleFullScreen()
{
_isFullScreen = !_isFullScreen;
SetFullScreen(_isFullScreen);
}
private void SetFullScreen(bool fullscreen)
{
if (fullscreen)
{
// 記錄原始狀態
_oldBounds = this.Bounds;
_oldWindowState = this.WindowState;
_oldFormBorderStyle = this.FormBorderStyle;
// 隱藏工作列
if (_taskbarHwnd != 0) ShowWindow(_taskbarHwnd, SW_HIDE);
// 設定工作區為全螢幕
Rectangle fullArea = Screen.FromControl(this).Bounds;
SystemParametersInfo(SPI_SETWORKAREA, 0, ref fullArea, SPIF_UPDATEINIFILE);
// 表單全螢幕
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
this.Bounds = Screen.FromControl(this).Bounds;
}
else
{
// 還原工作列
if (_taskbarHwnd != 0) ShowWindow(_taskbarHwnd, SW_SHOW);
// 還原工作區
SystemParametersInfo(SPI_SETWORKAREA, 0, ref _oldBounds, SPIF_UPDATEINIFILE);
// 還原表單
this.FormBorderStyle = _oldFormBorderStyle;
this.WindowState = _oldWindowState;
this.Bounds = _oldBounds;
}
}
private FormWindowState _oldWindowState;
private FormBorderStyle _oldFormBorderStyle;
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (_isFullScreen) SetFullScreen(false); // 確保關閉時還原工作列
base.OnFormClosing(e);
}
}
public partial class MainForm : FullScreenForm
{
public MainForm()
{
InitializeComponent();
// 可在按鈕點擊呼叫 ToggleFullScreen()
}
}
WPF 只需 `WindowState=Maximized; WindowStyle=None; ResizeMode=NoResize;` 即可真全螢幕,不需 P/Invoke。新專案建議考慮 WPF 或 WinUI 3。