如何在C#中实现窗口的始终置顶

   2024-10-01 2980
核心提示:在C#中,可以使用SetWindowPos函数来实现窗口的始终置顶。以下是一个示例代码:using System;using System.Runtime.InteropServi

在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方法用来取消始终置顶。通过调用这两个方法,可以实现窗口的始终置顶功能。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号