/// <summary> /// Get rectangle of a specified window. /// </summary> /// <param name="source">Source Window</param> internal static Rect GetWindowRect(Window source) { var handleWindow = new WindowInteropHelper(source).Handle; try { NativeMethod.RECT targetRect; // For Windows XP or older var result = NativeMethod.GetWindowRect( handleWindow, out targetRect); if (!result) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (OsVersion.IsVistaOrNewer) { // For Windows Vista or newer bool isEnabled = false; var result1 = NativeMethod.DwmIsCompositionEnabled( ref isEnabled); if (result1 != 0) // 0 means S_OK. { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (isEnabled) { var result2 = NativeMethod.DwmGetWindowAttribute( handleWindow, NativeMethod.DWMWA_EXTENDED_FRAME_BOUNDS, ref targetRect, Marshal.SizeOf(typeof(NativeMethod.RECT))); if (result2 != 0) // 0 means S_OK. { throw new Win32Exception(Marshal.GetLastWin32Error()); } } } return(targetRect.ToRect()); } catch (Win32Exception ex) { throw new Exception(String.Format("Failed to get window rect (Code: {0}).", ex.ErrorCode), ex); } }
/// <summary> /// Windows10のドロップシャドウ対策入りのキャプチャ /// </summary> /// <returns></returns> public static Bitmap CaptureActiveWindow10() { //アクティブなウィンドウのデバイスコンテキストを取得 IntPtr hWnd = WindowAPIWrapper.GetForegroundWindowHandle(); IntPtr hWinDC = NativeMethod.GetWindowDC(hWnd); //ウィンドウの大きさを取得 var winRect = new Rect(); Rect bounds; NativeMethod.DwmGetWindowAttribute(hWnd, DWMWINDOWATTRIBUTE.DWMWA_EXTENDED_FRAME_BOUNDS, out bounds, Marshal.SizeOf(typeof(Rect))); NativeMethod.GetWindowRect(hWnd, ref winRect); //Bitmapの作成 var offsetX = bounds.Left - winRect.Left; var offsetY = bounds.Top - winRect.Top; var bmp = new Bitmap(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top); //Graphicsの作成 using (var g = Graphics.FromImage(bmp)) { //Graphicsのデバイスコンテキストを取得 IntPtr hDC = g.GetHdc(); //Bitmapに画像をコピーする Int32 bmpWidth = bmp.Width; Int32 bmpHeight = bmp.Height; Console.WriteLine(winRect); NativeMethod.BitBlt(hDC, 0, 0, bmpWidth, bmpHeight, hWinDC, offsetX, offsetY, NativeMethod.SRCCOPY); //解放 g.ReleaseHdc(hDC); } NativeMethod.ReleaseDC(hWnd, hWinDC); return(bmp); }