有時候應用程序需要將一個窗體始終位於屏幕的最前面,即使切換到其它窗體也能看到該窗體,這樣的窗體就叫做TopMost窗體。
用C#制作TopMost窗體之前,首先要了解如何聲明SetWindowPos函數和SetWindowPos函數的具體功能,它們是制作TopMost窗體的關鍵,C#程序主要是通過調用Windows API函數中的SetWindowPos函數來實現。
SetWindowPos函數原型:BOOL SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int x, int y,int cx, int cy, UINT nFlags);
SetWindowPos函數功能:該函數改變一個子窗口,彈出式窗口或頂層窗口的尺寸,位置和Z序。子窗口,彈出式窗口,及頂層窗口根據它們在屏幕上出現的順序排序、頂層窗口設置的級別最高,並且被設置為Z序的第一個窗口。
SetWindowPos參數說明:
hWnd:被控制窗口的句柄。
hWndlnsertAfter:在z序中的位於被置位的窗口前的窗口句柄。該參數必須為一個窗口句柄,或下列值之一:
public class TopMostWindow
{
public const int HWND_TOP = 0;
public const int HWND_BOTTOM = 1;
public const int HWND_TOPMOST = -1;
public const int HWND_NOTOPMOST = -2;
[DllImport("user32.dll")]
public static extern IntPtr SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint wFlags);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out WindowRect lpRect);
/// <summary>
/// 設置窗體為TopMost
/// </summary>
/// <param name="hWnd"></param>
public static void SetTopomost(IntPtr hWnd)
{
WindowRect rect = new WindowRect();
GetWindowRect(hWnd, out rect);
SetWindowPos(hWnd, (IntPtr)HWND_TOPMOST, rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top, 0);
}
}
public struct WindowRect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
調用方式:
//將此窗體設置為Topmost
TopMostWindow.SetTopomost(new WindowInteropHelper(this).Handle);
備注:
HWND_BOTTOM,SWP_ASYNCWINDOWPOS等windows常量的值參考博客Windows API 常量定義