code:
namespace LOLMM { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Topmost = true; Loaded += new RoutedEventHandler(MainWindow_Loaded); t.Interval = TimeSpan.FromMilliseconds(300); t.Tick += new EventHandler(t_Tick); } DispatcherTimer t = new DispatcherTimer(); void t_Tick(object sender, EventArgs e) { TopMostWindow.SetTopomost(new WindowInteropHelper(this).Handle); } void MainWindow_Loaded(object sender, RoutedEventArgs e) { TopMostWindow.SetTopomost(new WindowInteropHelper(this).Handle); t.Start(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace LOLMM { public class TopMostWindow { public const int HWND_TOP = 0; public const int HWND_BOTTOM = 1; public const int HWND_TOPMOST = -1; public const int HWND_NOTOPMOST = -2; [DllImport("user32.dll")] public static extern IntPtr SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint wFlags); [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out WindowRect lpRect); /// <summary> /// 設置窗體為TopMost /// </summary> /// <param name="hWnd"></param> public static void SetTopomost(IntPtr hWnd) { WindowRect rect = new WindowRect(); GetWindowRect(hWnd, out rect); SetWindowPos(hWnd, (IntPtr)HWND_TOPMOST, rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top, 0); } } public struct WindowRect { public int Left; public int Top; public int Right; public int Bottom; } } //調用方式: //將此窗體設置為Topmost //TopMostWindow.SetTopomost(new WindowInteropHelper(this).Handle);