Example #1
0
        public static void TakeScreenshot(Screen screen, DateTime dateTimeScreenshotTaken, string format, string screenName, string path, int screenNumber, ScreenshotType screenshotType, long jpegQualityLevel, bool mouse)
        {
            try
            {
                if (!string.IsNullOrEmpty(path))
                {
                    Bitmap bitmap = screenNumber == 5 ? GetActiveWindowBitmap() : GetScreenBitmap(screen, Ratio, format, mouse);

                    if (bitmap != null)
                    {
                        Screenshot screenshot = new Screenshot(dateTimeScreenshotTaken, path, screenNumber, format, screenshotType == ScreenshotType.User ? ScreenshotCollection.Count : -1);

                        SaveToFile(bitmap, jpegQualityLevel, format, screenshot.Path, screenshotType);

                        ScreenshotCollection.Add(screenshot, screenshotType);

                        GC.Collect();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Write("ScreenCapture::TakeScreenshot", ex);
            }
        }
Example #2
0
        public static void TakeScreenshot(string name, string path, ImageFormat format, int jpegQuality, int resolutionRatio, bool mouse, int x, int y, int width, int height, bool addToScreenshotCollection)
        {
            try
            {
                if (!string.IsNullOrEmpty(path))
                {
                    Bitmap bitmap = GetScreenBitmap(x, y, width, height, Ratio, mouse);

                    if (bitmap != null)
                    {
                        if (addToScreenshotCollection)
                        {
                            ScreenshotCollection.Add(new Screenshot(name, DateTimePreviousScreenshot, path, format));
                        }

                        SaveToFile(path, format, jpegQuality, bitmap);

                        GC.Collect();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Write("ScreenCapture::TakeScreenshot(imageFormatCollection, x, y, width, height, path, jpegQualityLevel, mouse)", ex);
            }
        }
        public static void TakeScreenshot(string path, ImageFormat format, int component, ScreenshotType screenshotType,
                                          int jpegQuality, int resolutionRatio, bool mouse, int x, int y, int width, int height, Guid viewId,
                                          string label, ScreenCollection screenCollection, RegionCollection regionCollection)
        {
            try
            {
                Bitmap bitmap = component == 0
                    ? GetActiveWindowBitmap()
                    : GetScreenBitmap(x, y, width, height, Ratio, mouse);

                if (bitmap != null && !string.IsNullOrEmpty(path))
                {
                    FileInfo fileInfo = new FileInfo(path);

                    if (fileInfo.Directory != null && fileInfo.Directory.Root.Exists)
                    {
                        DriveInfo driveInfo = new DriveInfo(fileInfo.Directory.Root.FullName);

                        if (driveInfo.IsReady)
                        {
                            double freeDiskSpacePercentage =
                                (driveInfo.AvailableFreeSpace / (float)driveInfo.TotalSize) * 100;

                            if (freeDiskSpacePercentage > MIN_FREE_DISK_SPACE_PERCENTAGE)
                            {
                                string dirName = Path.GetDirectoryName(path);

                                if (!string.IsNullOrEmpty(dirName))
                                {
                                    if (!Directory.Exists(dirName))
                                    {
                                        Directory.CreateDirectory(dirName);
                                    }

                                    SaveToFile(path, format, jpegQuality, bitmap);

                                    ScreenshotCollection.Add(new Screenshot(DateTimePreviousScreenshot, path, format,
                                                                            component, screenshotType, GetActiveWindowTitle(), viewId, label),
                                                             screenCollection, regionCollection);
                                }
                            }
                        }
                    }

                    GC.Collect();
                }
            }
            catch (Exception ex)
            {
                Log.Write(
                    "ScreenCapture::TakeScreenshot(path, format, component, jpegQuality, resolutionRatio, mouse, x, y, width, height)",
                    ex);
            }
        }
Example #4
0
        private void AddScreenshotAndSaveToFile(int jpegQuality, Screenshot screenshot, ScreenshotCollection screenshotCollection)
        {
            string dirName = FileSystem.GetDirectoryName(screenshot.Path);

            if (string.IsNullOrEmpty(dirName))
            {
                Log.WriteDebugMessage("Directory name for screenshot with path \"" + screenshot.Path + "\" could not be found");

                return;
            }

            try
            {
                if (!FileSystem.DirectoryExists(dirName))
                {
                    FileSystem.CreateDirectory(dirName);

                    Log.WriteDebugMessage("Directory \"" + dirName + "\" did not exist so it was created");
                }

                if (screenshotCollection.Add(screenshot))
                {
                    SaveToFile(screenshot.Path, screenshot.Format, jpegQuality, screenshot.Bitmap);
                }
                else
                {
                    string hash = "hash";

                    if (!string.IsNullOrEmpty(screenshot.Hash))
                    {
                        hash = "hash (" + screenshot.Hash + ")";
                    }

                    Log.WriteDebugMessage("Could not save screenshot with path \"" + screenshot.Path + "\" because its " + hash + " may have matched with a previous hash that has already been used for an earlier screenshot");
                }
            }
            catch (Exception)
            {
                // We don't want to stop the screen capture session at this point because there may be other components that
                // can write to their given paths. If this is a misconfigured path for a particular component then just log an error.
                Log.WriteErrorMessage($"Cannot write to \"{screenshot.Path}\" because the user may not have the appropriate permissions to access the path");
            }
        }
Example #5
0
        /// <summary>
        /// Saves the captured bitmap image as a screenshot to an image file.
        /// </summary>
        /// <param name="path">The filepath of the image file to write to.</param>
        /// <param name="format">The format of the image file.</param>
        /// <param name="component">The component of the screenshot to be saved. This could be the active window or a screen.</param>
        /// <param name="screenshotType">The type of screenshot to save. This could be the active window, a region, or a screen.</param>
        /// <param name="jpegQuality">The JPEG quality setting for JPEG images being saved.</param>
        /// <param name="viewId">The unique identifier to identify a particular region or screen.</param>
        /// <param name="bitmap">The bitmap image to write to the image file.</param>
        /// <param name="label">The current label being used at the time of capture which we will apply to the screenshot object.</param>
        /// <param name="windowTitle">The title of the window being captured.</param>
        /// <param name="processName">The process name of the application being captured.</param>
        /// <param name="screenshotCollection">A collection of screenshot objects.</param>
        /// <returns>A boolean to determine if we successfully saved the screenshot.</returns>
        public bool SaveScreenshot(string path, ImageFormat format, int component, ScreenshotType screenshotType, int jpegQuality,
                                   Guid viewId, Bitmap bitmap, string label, string windowTitle, string processName, ScreenshotCollection screenshotCollection)
        {
            try
            {
                int  filepathLengthLimit   = Convert.ToInt32(Settings.Application.GetByKey("FilepathLengthLimit", DefaultSettings.FilepathLengthLimit).Value);
                bool optimizeScreenCapture = Convert.ToBoolean(Settings.Application.GetByKey("OptimizeScreenCapture", DefaultSettings.OptimizeScreenCapture).Value);

                if (!string.IsNullOrEmpty(path))
                {
                    if (path.Length > filepathLengthLimit)
                    {
                        Log.WriteMessage($"File path length exceeds the configured length of {filepathLengthLimit} characters so value was truncated. Correct the value for the FilepathLengthLimit application setting to prevent truncation");
                        path = path.Substring(0, filepathLengthLimit);
                    }

                    Log.WriteMessage("Attempting to write image to file at path \"" + path + "\"");

                    // This is a normal path used in Windows (such as "C:\screenshots\").
                    if (!path.StartsWith(FileSystem.PathDelimiter))
                    {
                        if (FileSystem.DriveReady(path))
                        {
                            int    lowDiskSpacePercentageThreshold = Convert.ToInt32(Settings.Application.GetByKey("LowDiskPercentageThreshold", DefaultSettings.LowDiskPercentageThreshold).Value);
                            double freeDiskSpacePercentage         = FileSystem.FreeDiskSpacePercentage(path);

                            Log.WriteDebugMessage("Percentage of free disk space on drive for \"" + path + "\" is " + (int)freeDiskSpacePercentage + "% and low disk percentage threshold is set to " + lowDiskSpacePercentageThreshold + "%");

                            if (freeDiskSpacePercentage > lowDiskSpacePercentageThreshold)
                            {
                                string dirName = FileSystem.GetDirectoryName(path);

                                if (!string.IsNullOrEmpty(dirName))
                                {
                                    if (!FileSystem.DirectoryExists(dirName))
                                    {
                                        FileSystem.CreateDirectory(dirName);

                                        Log.WriteDebugMessage("Directory \"" + dirName + "\" did not exist so it was created");
                                    }

                                    Screenshot lastScreenshotOfThisView = screenshotCollection.GetLastScreenshotOfView(viewId);

                                    Screenshot newScreenshotOfThisView = new Screenshot(windowTitle, DateTimeScreenshotsTaken)
                                    {
                                        ViewId         = viewId,
                                        Path           = path,
                                        Format         = format,
                                        Component      = component,
                                        ScreenshotType = screenshotType,
                                        ProcessName    = processName + ".exe",
                                        Label          = label
                                    };

                                    if (optimizeScreenCapture)
                                    {
                                        newScreenshotOfThisView.Hash = GetMD5Hash(bitmap, format);

                                        if (lastScreenshotOfThisView == null || string.IsNullOrEmpty(lastScreenshotOfThisView.Hash) ||
                                            !lastScreenshotOfThisView.Hash.Equals(newScreenshotOfThisView.Hash))
                                        {
                                            screenshotCollection.Add(newScreenshotOfThisView);

                                            SaveToFile(path, format, jpegQuality, bitmap);
                                        }
                                    }
                                    else
                                    {
                                        screenshotCollection.Add(newScreenshotOfThisView);

                                        SaveToFile(path, format, jpegQuality, bitmap);
                                    }
                                }
                            }
                            else
                            {
                                // There is not enough disk space on the drive so log an error message and change the system tray icon's colour to yellow.
                                Log.WriteErrorMessage($"Unable to save screenshot due to lack of available disk space on drive for {path} (at " + freeDiskSpacePercentage + "%) which is lower than the LowDiskPercentageThreshold setting that is currently set to " + lowDiskSpacePercentageThreshold + "%");

                                bool stopOnLowDiskError = Convert.ToBoolean(Settings.Application.GetByKey("StopOnLowDiskError", DefaultSettings.StopOnLowDiskError).Value);

                                if (stopOnLowDiskError)
                                {
                                    Log.WriteErrorMessage("Running screen capture session has stopped because application setting StopOnLowDiskError was set to True when the available disk space on any drive was lower than the value of LowDiskPercentageThreshold");

                                    ApplicationError = true;

                                    return(false);
                                }

                                ApplicationWarning = true;
                            }
                        }
                        else
                        {
                            // Drive isn't ready so log an error message.
                            Log.WriteErrorMessage($"Unable to save screenshot for \"{path}\" because the drive is not found or not ready");
                        }
                    }
                    else
                    {
                        // This is UNC network share path (such as "\\SERVER\screenshots\").
                        string dirName = FileSystem.GetDirectoryName(path);

                        if (!string.IsNullOrEmpty(dirName))
                        {
                            try
                            {
                                if (!FileSystem.DirectoryExists(dirName))
                                {
                                    FileSystem.CreateDirectory(dirName);

                                    Log.WriteDebugMessage("Directory \"" + dirName + "\" did not exist so it was created");
                                }

                                Screenshot lastScreenshotOfThisView = screenshotCollection.GetLastScreenshotOfView(viewId);

                                Screenshot newScreenshotOfThisView = new Screenshot(windowTitle, DateTimeScreenshotsTaken)
                                {
                                    ViewId         = viewId,
                                    Path           = path,
                                    Format         = format,
                                    Component      = component,
                                    ScreenshotType = screenshotType,
                                    ProcessName    = processName + ".exe",
                                    Label          = label
                                };

                                if (optimizeScreenCapture)
                                {
                                    newScreenshotOfThisView.Hash = GetMD5Hash(bitmap, format);

                                    if (lastScreenshotOfThisView == null || string.IsNullOrEmpty(lastScreenshotOfThisView.Hash) ||
                                        !lastScreenshotOfThisView.Hash.Equals(newScreenshotOfThisView.Hash))
                                    {
                                        screenshotCollection.Add(newScreenshotOfThisView);

                                        SaveToFile(path, format, jpegQuality, bitmap);
                                    }
                                }
                                else
                                {
                                    screenshotCollection.Add(newScreenshotOfThisView);

                                    SaveToFile(path, format, jpegQuality, bitmap);
                                }
                            }
                            catch (Exception)
                            {
                                // We don't want to stop the screen capture session at this point because there may be other components that
                                // can write to their given paths. If this is a misconfigured path for a particular component then just log an error.
                                Log.WriteErrorMessage($"Cannot write to \"{path}\" because the user may not have the appropriate permissions to access the path");
                            }
                        }
                    }
                }

                return(true);
            }
            catch (System.IO.PathTooLongException ex)
            {
                Log.WriteErrorMessage($"The path is too long. I see the path is \"{path}\" but the length exceeds what Windows can handle so the file could not be saved. There is probably an exception error from Windows explaining why");
                Log.WriteExceptionMessage("ScreenCapture::SaveScreenshot", ex);

                // This shouldn't be an error that should stop a screen capture session.
                return(true);
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("ScreenCapture::SaveScreenshot", ex);

                return(false);
            }
        }
Example #6
0
        public bool TakeScreenshot(string path, ImageFormat format, int component, ScreenshotType screenshotType,
                                   int jpegQuality, Guid viewId, Bitmap bitmap, string label, string windowTitle, string processName,
                                   ScreenCollection screenCollection, RegionCollection regionCollection, ScreenshotCollection screenshotCollection)
        {
            try
            {
                if (!string.IsNullOrEmpty(path))
                {
                    Log.Write("Attempting to write image to file at path \"" + path + "\"");

                    FileInfo fileInfo = new FileInfo(path);

                    if (fileInfo.Directory != null && fileInfo.Directory.Root.Exists)
                    {
                        DriveInfo driveInfo = new DriveInfo(fileInfo.Directory.Root.FullName);

                        if (driveInfo.IsReady)
                        {
                            double freeDiskSpacePercentage = (driveInfo.AvailableFreeSpace / (float)driveInfo.TotalSize) * 100;

                            Log.Write("Percentage of free disk space on drive " + fileInfo.Directory.Root.FullName + " is " + (int)freeDiskSpacePercentage + "%");

                            if (freeDiskSpacePercentage > MIN_FREE_DISK_SPACE_PERCENTAGE)
                            {
                                string dirName = Path.GetDirectoryName(path);

                                if (!string.IsNullOrEmpty(dirName))
                                {
                                    if (!Directory.Exists(dirName))
                                    {
                                        Directory.CreateDirectory(dirName);

                                        Log.Write("Directory \"" + dirName + "\" did not exist so it was created");
                                    }

                                    screenshotCollection.Add(new Screenshot(DateTimePreviousCycle, path, format, component, screenshotType, windowTitle, processName, viewId, label));

                                    SaveToFile(path, format, jpegQuality, bitmap);
                                }
                            }
                            else
                            {
                                Log.Write($"ERROR: Unable to save screenshot due to lack of available disk space on drive {fileInfo.Directory.Root.FullName} so screen capture session is being stopped");
                                return(false);
                            }
                        }
                        else
                        {
                            Log.Write("WARNING: Unable to save screenshot. Drive not ready");
                        }
                    }
                    else
                    {
                        Log.Write("WARNING: Unable to save screenshot. Directory root does not exist");
                    }
                }
                else
                {
                    Log.Write("No path available");
                    return(false);
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.Write("ScreenCapture::TakeScreenshot", ex);
                return(false);
            }
        }
Example #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="path"></param>
        /// <param name="format"></param>
        /// <param name="component"></param>
        /// <param name="screenshotType"></param>
        /// <param name="jpegQuality"></param>
        /// <param name="viewId"></param>
        /// <param name="bitmap"></param>
        /// <param name="label"></param>
        /// <param name="windowTitle"></param>
        /// <param name="processName"></param>
        /// <param name="screenshotCollection"></param>
        /// <returns></returns>
        public bool TakeScreenshot(string path, ImageFormat format, int component, ScreenshotType screenshotType, int jpegQuality,
                                   Guid viewId, Bitmap bitmap, string label, string windowTitle, string processName, ScreenshotCollection screenshotCollection)
        {
            try
            {
                if (!string.IsNullOrEmpty(path) && path.Length < MAX_WINDOWS_PATH_LENGTH)
                {
                    if (Log.DebugMode)
                    {
                        Log.Write("Attempting to write image to file at path \"" + path + "\"");
                    }

                    FileInfo fileInfo = new FileInfo(path);

                    if (fileInfo.Directory != null && fileInfo.Directory.Root.Exists)
                    {
                        // This is a normal path used in Windows (such as "C:\screenshots\").
                        if (!path.StartsWith(FileSystem.PathDelimiter))
                        {
                            DriveInfo driveInfo = new DriveInfo(fileInfo.Directory.Root.FullName);

                            if (driveInfo.IsReady)
                            {
                                double freeDiskSpacePercentage = (driveInfo.AvailableFreeSpace / (float)driveInfo.TotalSize) * 100;

                                if (Log.DebugMode)
                                {
                                    Log.Write("Percentage of free disk space on drive " + fileInfo.Directory.Root.FullName + " is " + (int)freeDiskSpacePercentage + "%");
                                }

                                if (freeDiskSpacePercentage > MIN_FREE_DISK_SPACE_PERCENTAGE)
                                {
                                    string dirName = Path.GetDirectoryName(path);

                                    if (!string.IsNullOrEmpty(dirName))
                                    {
                                        if (!Directory.Exists(dirName))
                                        {
                                            Directory.CreateDirectory(dirName);

                                            Log.Write("Directory \"" + dirName + "\" did not exist so it was created");
                                        }

                                        screenshotCollection.Add(new Screenshot(DateTimePreviousCycle, path, format, component, screenshotType, windowTitle, processName, viewId, label));

                                        SaveToFile(path, format, jpegQuality, bitmap);
                                    }
                                }
                                else
                                {
                                    Log.Write($"ERROR: Unable to save screenshot due to lack of available disk space on drive {fileInfo.Directory.Root.FullName} so screen capture session is being stopped");
                                    return(false);
                                }
                            }
                            else
                            {
                                Log.Write("WARNING: Unable to save screenshot. Drive not ready");
                            }
                        }
                        else
                        {
                            // This is UNC network share path (such as "\\SERVER\screenshots\").
                            string dirName = Path.GetDirectoryName(path);

                            if (!string.IsNullOrEmpty(dirName))
                            {
                                if (!Directory.Exists(dirName))
                                {
                                    Directory.CreateDirectory(dirName);

                                    Log.Write("Directory \"" + dirName + "\" did not exist so it was created");
                                }

                                screenshotCollection.Add(new Screenshot(DateTimePreviousCycle, path, format, component, screenshotType, windowTitle, processName, viewId, label));

                                SaveToFile(path, format, jpegQuality, bitmap);
                            }
                        }
                    }
                    else
                    {
                        Log.Write("WARNING: Unable to save screenshot. Directory root does not exist");
                    }
                }
                else
                {
                    Log.Write($"No path available or path length exceeds {MAX_WINDOWS_PATH_LENGTH} characters");

                    return(false);
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.Write("ScreenCapture::TakeScreenshot", ex);

                return(false);
            }
        }
Example #8
0
        /// <summary>
        /// Saves the captured bitmap image as a screenshot to an image file.
        /// </summary>
        /// <param name="path">The filepath of the image file to write to.</param>
        /// <param name="format">The format of the image file.</param>
        /// <param name="component">The component of the screenshot to be saved. This could be the active window or a screen.</param>
        /// <param name="screenshotType">The type of screenshot to save. This could be the active window, a region, or a screen.</param>
        /// <param name="jpegQuality">The JPEG quality setting for JPEG images being saved.</param>
        /// <param name="viewId">The unique identifier to identify a particular region or screen.</param>
        /// <param name="bitmap">The bitmap image to write to the image file.</param>
        /// <param name="label">The current label being used at the time of capture which we will apply to the screenshot object.</param>
        /// <param name="windowTitle">The title of the window being captured.</param>
        /// <param name="processName">The process name of the application being captured.</param>
        /// <param name="screenshotCollection">A collection of screenshot objects.</param>
        /// <returns>A boolean to determine if we successfully saved the screenshot.</returns>
        public bool SaveScreenshot(string path, ImageFormat format, int component, ScreenshotType screenshotType, int jpegQuality,
                                   Guid viewId, Bitmap bitmap, string label, string windowTitle, string processName, ScreenshotCollection screenshotCollection)
        {
            try
            {
                if (!string.IsNullOrEmpty(path) && path.Length >= MAX_WINDOWS_PATH_LENGTH)
                {
                    // We just want to log a normal message and not stop the screen capture session because we want to continue
                    // for other components that are using paths which are still valid.
                    Log.WriteMessage($"No path available at \"{path}\" or path length exceeds {MAX_WINDOWS_PATH_LENGTH} characters");
                }

                if (!string.IsNullOrEmpty(path) && path.Length < MAX_WINDOWS_PATH_LENGTH)
                {
                    Log.WriteDebugMessage("Attempting to write image to file at path \"" + path + "\"");

                    // This is a normal path used in Windows (such as "C:\screenshots\").
                    if (!path.StartsWith(FileSystem.PathDelimiter))
                    {
                        if (FileSystem.DriveReady(path))
                        {
                            int    lowDiskSpacePercentageThreshold = Convert.ToInt32(Settings.Application.GetByKey("LowDiskPercentageThreshold", defaultValue: 1).Value);
                            double freeDiskSpacePercentage         = FileSystem.FreeDiskSpacePercentage(path);

                            Log.WriteDebugMessage("Percentage of free disk space on drive for \"" + path + "\" is " + (int)freeDiskSpacePercentage + "% and low disk percentage threshold is set to " + lowDiskSpacePercentageThreshold + "%");

                            if (freeDiskSpacePercentage > lowDiskSpacePercentageThreshold)
                            {
                                string dirName = FileSystem.GetDirectoryName(path);

                                if (!string.IsNullOrEmpty(dirName))
                                {
                                    if (!FileSystem.DirectoryExists(dirName))
                                    {
                                        FileSystem.CreateDirectory(dirName);

                                        Log.WriteDebugMessage("Directory \"" + dirName + "\" did not exist so it was created");
                                    }

                                    Screenshot screenshot = new Screenshot(DateTimeScreenshotsTaken, path, format, component, screenshotType, windowTitle, processName, viewId, label);

                                    screenshotCollection.Add(screenshot);

                                    SaveToFile(path, format, jpegQuality, bitmap);
                                }
                            }
                            else
                            {
                                // There is not enough disk space on the drive so stop the current running screen capture session and log an error message.
                                Log.WriteErrorMessage($"Unable to save screenshot due to lack of available disk space on drive for {path} (at " + freeDiskSpacePercentage + "%) which is lower than the LowDiskPercentageThreshold setting that is currently set to " + lowDiskSpacePercentageThreshold + "% so screen capture session is being stopped");

                                return(false);
                            }
                        }
                        else
                        {
                            // Drive isn't ready so log an error message.
                            Log.WriteErrorMessage($"Unable to save screenshot for \"{path}\" because the drive is not found or not ready");
                        }
                    }
                    else
                    {
                        // This is UNC network share path (such as "\\SERVER\screenshots\").
                        string dirName = FileSystem.GetDirectoryName(path);

                        if (!string.IsNullOrEmpty(dirName))
                        {
                            try
                            {
                                if (!FileSystem.DirectoryExists(dirName))
                                {
                                    FileSystem.CreateDirectory(dirName);

                                    Log.WriteDebugMessage("Directory \"" + dirName + "\" did not exist so it was created");
                                }

                                screenshotCollection.Add(new Screenshot(DateTimeScreenshotsTaken, path, format, component, screenshotType, windowTitle, processName, viewId, label));

                                SaveToFile(path, format, jpegQuality, bitmap);
                            }
                            catch (Exception)
                            {
                                // We don't want to stop the screen capture session at this point because there may be other components that
                                // can write to their given paths. If this is a misconfigured path for a particular component then just log an error.
                                Log.WriteErrorMessage($"Cannot write to \"{path}\" because the user may not have the appropriate permissions to access the path");
                            }
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("ScreenCapture::SaveScreenshot", ex);

                return(false);
            }
        }