在C#中,可以使用SetWindowPos
函數(shù)來實(shí)現(xiàn)窗口的始終置頂。以下是一個(gè)示例代碼:
using System;
using System.Runtime.InteropServices;
public class WindowHelper
{
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
public const uint SWP_NOSIZE = 0x0001;
public const uint SWP_NOMOVE = 0x0002;
public const uint SWP_SHOWWINDOW = 0x0040;
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
public static void SetTopMost(IntPtr hWnd)
{
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
}
public static void SetNotTopMost(IntPtr hWnd)
{
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
}
}
使用示例:
using System;
using System.Windows.Forms;
public class MainForm : Form
{
public MainForm()
{
this.Text = "Top Most Window Example";
this.Size = new System.Drawing.Size(300, 200);
// 設(shè)置窗口為始終置頂
WindowHelper.SetTopMost(this.Handle);
// 取消窗口的始終置頂
// WindowHelper.SetNotTopMost(this.Handle);
}
}
在上面的示例中,SetTopMost
方法用來將窗口設(shè)置為始終置頂,SetNotTopMost
方法用來取消始終置頂。通過調(diào)用這兩個(gè)方法,可以實(shí)現(xiàn)窗口的始終置頂功能。