`SetWindowPos` 是 Windows API 中控制視窗 Z-Order、位置、大小、顯示狀態的核心函式。C# 透過 P/Invoke 呼叫,可實現視窗置頂、置底、不啟動顯示等效果。
using System;
using System.Runtime.InteropServices;
public static class Win32
{
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
// hWndInsertAfter 特殊值
public static readonly IntPtr HWND_TOP = new IntPtr(0); // 置頂 (非最上層)
public static readonly IntPtr HWND_BOTTOM = new IntPtr(1); // 置底
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); // 永久置頂 (Topmost)
public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); // 取消永久置頂
// uFlags 常用組合
public const uint SWP_NOSIZE = 0x0001;
public const uint SWP_NOMOVE = 0x0002;
public const uint SWP_NOZORDER = 0x0004;
public const uint SWP_NOREDRAW = 0x0008;
public const uint SWP_NOACTIVATE = 0x0010; // 不搶焦點
public const uint SWP_SHOWWINDOW = 0x0040;
public const uint SWP_HIDEWINDOW = 0x0080;
public const uint SWP_FRAMECHANGED = 0x0020; // 強制重繪非客戶區
}
// Form_Load 或按鈕事件
Win32.SetWindowPos(this.Handle, Win32.HWND_TOPMOST, 0, 0, 0, 0, Win32.SWP_NOMOVE | Win32.SWP_NOSIZE);
Win32.SetWindowPos(this.Handle, Win32.HWND_NOTOPMOST, 0, 0, 0, 0, Win32.SWP_NOMOVE | Win32.SWP_NOSIZE);
var frm = new Form2();
frm.Show(); // 非 ShowDialog
// 取得剛建立視窗的 Handle (需等待 Handle 建立)
this.BeginInvoke((Action)(() =>
{
Win32.SetWindowPos(frm.Handle, Win32.HWND_TOPMOST, 0, 0, 0, 0,
Win32.SWP_NOMOVE | Win32.SWP_NOSIZE | Win32.SWP_NOACTIVATE);
}));
Win32.SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, Win32.SWP_HIDEWINDOW | Win32.SWP_NOSIZE | Win32.SWP_NOMOVE | Win32.SWP_NOACTIVATE);
// 顯示
Win32.SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, Win32.SWP_SHOWWINDOW | Win32.SWP_NOSIZE | Win32.SWP_NOMOVE | Win32.SWP_NOACTIVATE);
IntPtr fg = Win32.GetForegroundWindow();
if (fg != IntPtr.Zero)
Win32.SetWindowPos(fg, Win32.HWND_TOPMOST, 0, 0, 0, 0, Win32.SWP_NOMOVE | Win32.SWP_NOSIZE);
| 需求 | uFlags 組合 |
|---|---|
| 僅改 Z-Order (置頂/置底) | SWP_NOMOVE | SWP_NOSIZE |
| 移動+縮放+置頂 | SWP_NOZORDER (不設) → 直接給座標 |
| 不搶焦點置頂 | SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE |
| 隱藏不銷毀 | SWP_HIDEWINDOW | SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE |