WindowHelper.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*************************************************************************************
  2. Extended WPF Toolkit
  3. Copyright (C) 2007-2013 Xceed Software Inc.
  4. This program is provided to you under the terms of the Microsoft Public
  5. License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
  6. For more features, controls, and fast professional support,
  7. pick up the Plus Edition at http://xceed.com/wpf_toolkit
  8. Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
  9. ***********************************************************************************/
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Windows.Media;
  15. using System.Windows;
  16. using System.Windows.Interop;
  17. namespace Xceed.Wpf.AvalonDock
  18. {
  19. static class WindowHelper
  20. {
  21. public static bool IsAttachedToPresentationSource(this Visual element)
  22. {
  23. return PresentationSource.FromVisual(element as Visual) != null;
  24. }
  25. public static void SetParentToMainWindowOf(this Window window, Visual element)
  26. {
  27. var wndParent = Window.GetWindow(element);
  28. if (wndParent != null)
  29. window.Owner = wndParent;
  30. else
  31. {
  32. IntPtr parentHwnd;
  33. if (GetParentWindowHandle(element, out parentHwnd))
  34. Win32Helper.SetOwner(new WindowInteropHelper(window).Handle, parentHwnd);
  35. }
  36. }
  37. public static IntPtr GetParentWindowHandle(this Window window)
  38. {
  39. if (window.Owner != null)
  40. return new WindowInteropHelper(window.Owner).Handle;
  41. else
  42. return Win32Helper.GetOwner(new WindowInteropHelper(window).Handle);
  43. }
  44. public static bool GetParentWindowHandle(this Visual element, out IntPtr hwnd)
  45. {
  46. hwnd = IntPtr.Zero;
  47. HwndSource wpfHandle = PresentationSource.FromVisual(element) as HwndSource;
  48. if (wpfHandle == null)
  49. return false;
  50. hwnd = Win32Helper.GetParent(wpfHandle.Handle);
  51. if (hwnd == IntPtr.Zero)
  52. hwnd = wpfHandle.Handle;
  53. return true;
  54. }
  55. public static void SetParentWindowToNull(this Window window)
  56. {
  57. if (window.Owner != null)
  58. window.Owner = null;
  59. else
  60. {
  61. Win32Helper.SetOwner(new WindowInteropHelper(window).Handle, IntPtr.Zero);
  62. }
  63. }
  64. }
  65. }