C#或者WPF中让某个窗体置顶

前记:在工作中有个需求,要求不管到那个界面,我必须让一个浮动条(其实是个窗体)置顶。

我用wpf,因为有之前有好几个界面已经设置成topmost了,所以在这几个界面,我的浮动条会被遮挡。为了始终让浮动条在最顶端,我写了个简单的工具类。在前面已经设置成topmost的窗体的Window_Loaded中调用这个工具类里的方法实现了始终让浮动条置顶。
工具类代码如下:

public class TopMostTool
{
    public static  int SW_SHOW = 5;
    public static  int SW_NORMAL = 1;
    public static  int SW_MAX = 3;
    public static  int SW_HIDE = 0;
    public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);    //窗体置顶
    public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);    //取消窗体置顶
    public const uint SWP_NOMOVE = 0x0002;    //不调整窗体位置
    public const uint SWP_NOSIZE = 0x0001;    //不调整窗体大小
    public bool isFirst = true;

    [DllImport("user32.dll")]
    public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);

    [DllImport("user32.dll", EntryPoint = "ShowWindow")]
    public static extern bool ShowWindow(System.IntPtr hWnd, int nCmdShow);

    [DllImport("user32.dll")]
    FindWindow(string lpClassName,string lpWindowName);

    /// <summary>
    /// 在外面的方法中掉用这个方法就可以让浮动条(CustomBar)始终置顶
    /// CustomBar是我的程序中需要置顶的窗体的名字,你们可以根据需要传入不同的值
    /// </summary>
    public static void setTopCustomBar(){
        IntPtr CustomBar = FindWindow(null,"CustomBar");    //CustomBar是我的程序中需要置顶的窗体的名字
        if(CustomBar!=null){
            SetWindowPos(CustomBar, MainWindow.HWND_TOPMOST, 0, 0, 0, 0, MainWindow.SWP_NOMOVE | MainWindow.SWP_NOSIZE);
        }
    }
}

这个类里的几个方法详解
SetWindowPos方法详解请戳这里
ShowWindow方法详解请戳这里
FindWindow方法详解请戳这里
写的比较粗糙,就当给自己做笔记!

WPFWindows Presentation Foundation),如果你想要创建一个不能被最小化的窗口,可以通过设置窗口的`WindowStyle`属性来实现。具体操作步骤如下: 1. 打开你的WPF项目,并找到你想要修改的窗口的XAML文件。 2. 在窗口的根元素上设置`WindowStyle`属性为"None"。这将移除窗口的最小化、最大化和关闭按钮。 3. 同时,为了防止用户通过其他方式最小化窗口,例如通过拖动窗口标题栏到屏幕的顶部,你需要在窗口的代码后台(code-behind)设置窗口的`ResizeMode`属性为"NoResize"。 以下是具体的XAML和C#代码示例: XAML代码: ```xml <Window x:Class="YourNamespace.YourWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" WindowStyle="None" ResizeMode="NoResize" Title="Your Window Title" Height="350" Width="525"> <!-- Your window content goes here --> </Window> ``` C#代码(在窗口的构造函数): ```csharp public YourWindow() { InitializeComponent(); this.WindowStyle = WindowStyle.None; this.ResizeMode = ResizeMode.NoResize; } ``` 请注意,当窗口样式设置为"None"时,窗口将不再有标题栏、最小化按钮、最大化按钮和关闭按钮,这意味着用户不能通过标准的窗口控制来最小化或关闭窗口。如果需要,你可能需要提供自定义的最小化和关闭机制,例如添加自定义按钮和处理它们的点击事件。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值