在C#中,可以使用SetWindowPos
函數來實現窗口的始終置頂。以下是一個示例代碼:
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);
// 設置窗口為始終置頂
WindowHelper.SetTopMost(this.Handle);
// 取消窗口的始終置頂
// WindowHelper.SetNotTopMost(this.Handle);
}
}
在上面的示例中,SetTopMost
方法用來將窗口設置為始終置頂,SetNotTopMost
方法用來取消始終置頂。通過調用這兩個方法,可以實現窗口的始終置頂功能。