Exemplo n.º 1
0
        /// <summary>
        /// Provides enumeration of screenshots of a specific application window.
        /// </summary>
        /// <param name="applicationName">The title of the main application window.</param>
        /// <param name="isDisplayCursor">Whether to display the cursor in screenshots.</param>
        /// <returns>Enumeration of screenshots of a specific application window.</returns>
        public static IEnumerable <Image> TakeSeriesOfScreenshotsAppWindow(string applicationName,
                                                                           bool isDisplayCursor)
        {
            var windowHandle = ApplicationWindow.FindWindow(null, applicationName);

            var screeRectangle = new Rectangle();

            while (true)
            {
                ApplicationWindow.GetWindowRect(windowHandle, ref screeRectangle);

                screeRectangle.Width  -= screeRectangle.X;
                screeRectangle.Height -= screeRectangle.Y;

                var image = new Bitmap(screeRectangle.Width, screeRectangle.Height);

                var graphics = Graphics.FromImage(image);

                var hdc = graphics.GetHdc();

                if (!ApplicationWindow.PrintWindow(windowHandle, hdc,
                                                   ApplicationWindow.DrawAllWindow))
                {
                    int error = Marshal.GetLastWin32Error();
                    throw new System.ComponentModel.Win32Exception($"An error occurred while creating a screenshot"
                                                                   + $" of the application window. Error Number: {error}.");
                }

                graphics.ReleaseHdc(hdc);

                if (isDisplayCursor)
                {
                    AddCursorToScreenshot(graphics, screeRectangle);
                }

                yield return(image);

                image.Dispose();
                graphics.Dispose();
            }
        }