星期一, 3月 28, 2022

[C#] 全螢幕

了解如何把 Form 產生全螢幕效果,該筆記是採取根據螢幕解析度來設定 Form 大小,並蓋過整個工作列

拉一個 Form 並放置兩個 Button,一個全螢幕、另一個回復
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace FormFullScreen
{
    public partial class Form1 : Form
    {
        #region 螢幕解析度相關

        // The width of the screen of the primary display monitor, in pixels.
        private const int SM_CXSCREEN = 0;
        // The height of the screen of the primary display monitor, in pixels.
        private const int SM_CYSCREEN = 1;

        [DllImport("user32.dll", EntryPoint = "GetSystemMetrics")]
        public static extern int GetSystemMetrics(int nIndex);

        #endregion

        #region 設定視窗相關

        // Places the window at the top of the Z order.
        private IntPtr HWND_TOP = IntPtr.Zero;
        // Places the window above all non-topmost windows
        private IntPtr HWND_TOPMOST = new IntPtr(-1);
        // Displays the window.
        private const int SWP_SHOWWINDOW = 64; // 0x0040

        [DllImport("user32.dll")]
        public static extern void SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int X, int Y, int width, int height, uint flags);

        #endregion

        public Form1()
        {
            InitializeComponent();
        }

        private void btnFullScreen_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            this.FormBorderStyle = FormBorderStyle.None;
            this.TopMost = true;

            // 根據解析度設定 Form,會蓋過整個工作列
            SetWindowPos(this.Handle, HWND_TOP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_SHOWWINDOW);
        }

        private void btnNormal_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.FormBorderStyle = FormBorderStyle.Sizable;
            this.TopMost = false;
        }
    }
}
看 SetWindowPos 時發現,找到文章都是透過 Form.TopMost 搭配 HWND_TOP 參數,但其實有 HWND_TOPMOST 可以直接使用
this.TopMost = true;
SetWindowPos(this.Handle, HWND_TOP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_SHOWWINDOW);
// 或
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_SHOWWINDOW);
而螢幕解析度,習慣使用 SystemInformation 來得到
SystemInformation.PrimaryMonitorSize.Width;
SystemInformation.PrimaryMonitorSize.Height;
按 F12 發現,骨子裡還是透過 WinAPI 得到的
public static Size PrimaryMonitorSize => new Size(UnsafeNativeMethods.GetSystemMetrics(0), UnsafeNativeMethods.GetSystemMetrics(1));

1 則留言: