萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

C# SetWindowPos 置頂視窗、置底、顯示/隱藏完整用法

前言

`SetWindowPos` 是 Windows API 中控制視窗 Z-Order、位置、大小、顯示狀態的核心函式。C# 透過 P/Invoke 呼叫,可實現視窗置頂、置底、不啟動顯示等效果。

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; // 強制重繪非客戶區
}

常見使用場景

1. 視窗永久置頂

// Form_Load 或按鈕事件
Win32.SetWindowPos(this.Handle, Win32.HWND_TOPMOST, 0, 0, 0, 0, Win32.SWP_NOMOVE | Win32.SWP_NOSIZE);

2. 取消置頂

Win32.SetWindowPos(this.Handle, Win32.HWND_NOTOPMOST, 0, 0, 0, 0, Win32.SWP_NOMOVE | Win32.SWP_NOSIZE);

3. 彈出新視窗並置頂 (不搶焦點)

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);
}));

4. 隱藏/顯示視窗 (不觸發 FormClosing)

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);

5. 取得目前前景視窗並置頂

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

注意事項

  • `SetWindowPos` 為**同步阻塞**呼叫,UI 執行緒會等待完成。
  • `HWND_TOPMOST` 視窗會蓋過**所有**非 Topmost 視窗 (含工作列、開始功能表),濫用會嚴重影響使用者體驗。
  • 若需「僅在應用程式內置頂」,請改用 `Form.TopMost = true` (WinForms) 或 `Window.Topmost = true` (WPF),由框架管理 Z-Order。
  • 錯誤處理:`SetLastError=true` 失敗時呼叫 `Marshal.GetLastWin32Error()` 取得錯誤碼。
copyright © 萬盛學電腦網 all rights reserved