C#或者WPF中讓某個窗體置頂
阿新 • • 發佈:2018-11-03
原文:
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方法詳解請戳這裡
寫的比較粗糙,就當給自己做筆記!