WPF PopupNonTopmost重写

之前做WPF遇到问题,在网上找到的一个类

 1     public class PopupNonTopmost : System.Windows.Controls.Primitives.Popup
 2     {
 3         public static DependencyProperty TopmostProperty = Window.TopmostProperty.AddOwner(
 4         typeof(PopupNonTopmost),
 5         new FrameworkPropertyMetadata(false, OnTopmostChanged));
 6 
 7         public bool Topmost
 8         {
 9             get { return (bool)GetValue(TopmostProperty); }
10             set { SetValue(TopmostProperty, value); }
11         }
12 
13         private static void OnTopmostChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
14         {
15             (obj as PopupNonTopmost).UpdateWindow();
16         }
17 
18         protected override void OnOpened(EventArgs e)
19         {
20             UpdateWindow();
21         }
22 
23         private void UpdateWindow()
24         {
25             var hwnd = ((HwndSource)PresentationSource.FromVisual(this.Child)).Handle;
26             RECT rect;
27 
28             if (GetWindowRect(hwnd, out rect))
29             {
30                 SetWindowPos(hwnd, Topmost ? -1 : -2, rect.Left, rect.Top, (int)this.Width, (int)this.Height, 0);
31             }
32         }
33 
34         #region P/Invoke imports & definitions
35 
36         [StructLayout(LayoutKind.Sequential)]
37         public struct RECT
38         {
39             public int Left;
40             public int Top;
41             public int Right;
42             public int Bottom;
43         }
44 
45         [DllImport("user32.dll")]
46         [return: MarshalAs(UnmanagedType.Bool)]
47         private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
48 
49         [DllImport("user32", EntryPoint = "SetWindowPos")]
50         private static extern int SetWindowPos(IntPtr hWnd, int hwndInsertAfter, int x, int y, int cx, int cy, int wFlags);
51 
52         #endregion
53     }
posted @ 2014-07-22 13:42  b̶i̶n̶g̶.̶  阅读(431)  评论(0编辑  收藏  举报