当前位置:首页 > C#教程 > C#高级

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

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

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

publicclass topmosttool
{
    publicstaticint sw_show = 5;
    publicstaticint sw_normal = 1;
    publicstaticint sw_max = 3;
    publicstaticint sw_hide = 0;

publicstaticreadonly intptr hwnd_topmost = new intptr(-1);  

//窗体置顶

publicstaticreadonly intptr hwnd_notopmost = new intptr(-2);  

//取消窗体置顶

publicconstuint swp_nomove = 0x0002; //不调整窗体位置

publicconstuint swp_nosize = 0x0001; //不调整窗体大小

publicbool isfirst = true;

[dllimport("user32.dll")] publicstaticexternboolsetwindowpos(intptr hwnd, intptr hwndinsertafter, int x, int y, int cx, int cy, uint uflags); [dllimport("user32.dll", entrypoint = "showwindow")] publicstaticexternboolshowwindow(system.intptr hwnd, int ncmdshow); [dllimport("user32.dll")] findwindow(string lpclassname,string lpwindowname); ///<summary>/// 在外面的方法中掉用这个方法就可以让浮动条(custombar)始终置顶/// custombar是我的程序中需要置顶的窗体的名字,你们可以根据需要传入不同的值///</summary>publicstaticvoidsettopcustombar(){ intptr custombar = findwindow(null,"custombar"); //custombar是我的程序中需要置顶的窗体的名字if(custombar!=null){ setwindowpos(custombar, mainwindow.hwnd_topmost, 0, 0, 0, 0, mainwindow.swp_nomove | mainwindow.swp_nosize); } } }

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!