最近遇到一個需要將WPF窗體一直置頂的需求
試驗了一種方案,記錄一下
wpf窗體的句柄獲取方式,在window窗體load事件中獲取窗體句柄,供下面調用windowAPI使用
IntPtr handle;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
WindowInteropHelper wndHelper = new WindowInteropHelper(this);
handle = wndHelper.Handle;
}
有了窗口句柄接下來就是調用API,搞個線程,每隔500ms設置一下窗體置頂, 試驗了一下SWP_NOMOVE, SWP_SHOWWINDOW單獨使用這兩個參數就可以
[DllImport("user32.dll")]
private static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
const int SWP_SHOWWINDOW = 0x0040;
const int SWP_NOMOVE = 0x2;
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
new Thread(()=> {
while(true)
{
Thread.Sleep(500);
Application.Current.Dispatcher.Invoke(()=> {
SetWindowPos(handle, HWND_TOPMOST, 0, 0, 500, 500, SWP_SHOWWINDOW);
});
}
}).Start();
這麼幹以後,你的窗體就一直在最上面。使用的話儘量不要窗體裏幹太多事,否則可能稍稍影響性能