温馨提示×

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

c#
小樊
249
2024-08-13 08:05:41
栏目: 编程语言

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

0