您的位置:首页 > 编程语言 > C#

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

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

我用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方法详解请戳这里

写的比较粗糙,就当给自己做笔记!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  wpf 置顶 窗体