/// <summary> /// Creates a Snapshot instance from a Wpf Window. /// </summary> /// <param name="window">The Wpf Window, identifying the window to capture from.</param> /// <param name="windowSnapshotMode">Determines if window border region should captured as part of Snapshot.</param> /// <returns>A Snapshot instance of the pixels captured.</returns> public static Snapshot SnapshotFromWindow(Visual window, WindowSnapshotMode windowSnapshotMode) { Snapshot result; HwndSource source = (HwndSource)PresentationSource.FromVisual(window); if (source == null) { throw new InvalidOperationException("The specified Window is not being rendered."); } IntPtr windowHandle = source.Handle; result = Snapshot.FromWindow(windowHandle, windowSnapshotMode); return(result); }
/// <summary> /// Creates a Snapshot instance populated with pixels sampled from the rectangle of the specified window. /// </summary> /// <param name="windowHandle">The Win32 window handle (also known as an HWND), identifying the window to capture from.</param> /// <param name="windowSnapshotMode">Determines if window border region should captured as part of Snapshot.</param> /// <returns>A Snapshot instance of the pixels captured.</returns> public static Snapshot FromWindow(IntPtr windowHandle, WindowSnapshotMode windowSnapshotMode) { Snapshot result; RECT rect; if (windowSnapshotMode == WindowSnapshotMode.ExcludeWindowBorder) { if (!NativeMethods.GetClientRect(windowHandle, out rect)) { throw new Win32Exception(); } IntPtr deviceContext = NativeMethods.GetDC(windowHandle); try { if (deviceContext == IntPtr.Zero) { throw new Win32Exception(); } result = FromBitmap(CaptureBitmap(deviceContext, rect.ToRectangle())); } finally { NativeMethods.ReleaseDC(windowHandle, deviceContext); } } else if (windowSnapshotMode == WindowSnapshotMode.IncludeWindowBorder) { if (!NativeMethods.GetWindowRect(windowHandle, out rect)) { throw new Win32Exception(); } result = FromRectangle(rect.ToRectangle()); } else { throw new ArgumentOutOfRangeException("windowSnapshotMode"); } return(result); }