在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
方法用来取消始终置顶。通过调用这两个方法,可以实现窗口的始终置顶功能。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: c#中debug如何看程序运行结果