Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 3
0
        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);
            }
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="log">The logging class.</param>
        /// <param name="config">Configuration.</param>
        /// <param name="security">Security.</param>
        /// <param name="fileSystem">File system.</param>
        /// <param name="screenshotCollection">Screenshot collection.</param>
        public FormEncryptorDecryptor(Log log, Config config, Security security, FileSystem fileSystem, ScreenshotCollection screenshotCollection)
        {
            InitializeComponent();

            _screenshotsLoadLimit = Convert.ToInt32(config.Settings.Application.GetByKey("ScreenshotsLoadLimit", config.Settings.DefaultSettings.ScreenshotsLoadLimit).Value);

            _log                  = log;
            _security             = security;
            _fileSystem           = fileSystem;
            _screenshotCollection = screenshotCollection;

            runScreenshotLoad = new BackgroundWorker
            {
                WorkerReportsProgress      = false,
                WorkerSupportsCancellation = true
            };

            runScreenshotLoad.DoWork             += new DoWorkEventHandler(DoWork_runScreenshotLoad);
            runScreenshotLoad.RunWorkerCompleted += RunScreenshotLoad_RunWorkerCompleted;

            runScreenshotsEncryption = new BackgroundWorker
            {
                WorkerReportsProgress      = false,
                WorkerSupportsCancellation = true
            };

            runScreenshotsEncryption.DoWork             += new DoWorkEventHandler(DoWork_runScreenshotsEncryption);
            runScreenshotsEncryption.RunWorkerCompleted += RunScreenshotsEncryption_RunWorkerCompleted;

            runScreenshotsDecryption = new BackgroundWorker
            {
                WorkerReportsProgress      = false,
                WorkerSupportsCancellation = true
            };

            runScreenshotsDecryption.DoWork             += new DoWorkEventHandler(DoWork_runScreenshotsDecryption);
            runScreenshotsDecryption.RunWorkerCompleted += RunScreenshotsDecryption_RunWorkerCompleted;
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Loads the user's saved settings.
        /// </summary>
        private void LoadSettings()
        {
            try
            {
                Log.WriteMessage("*** Welcome to " + Settings.ApplicationName + " " + Settings.ApplicationVersion + " (\"" + Settings.ApplicationCodename + "\") ***");
                Log.WriteMessage("Starting application");
                Log.WriteDebugMessage("At this point the application should be able to run normally");
                Log.WriteDebugMessage("but it would be a good idea to check what we found in your autoscreen.conf file");
                Log.WriteDebugMessage("Your autoscreen.conf file is \"" + FileSystem.ConfigFile + "\"");
                Log.WriteDebugMessage("The name and location of it can be changed with the -config command line argument:");
                Log.WriteDebugMessage("autoscreen.exe -config=C:\\MyAutoScreenCapture.conf");
                Log.WriteDebugMessage("Checking what we loaded from your autoscreen.conf file ...");
                Log.WriteDebugMessage("ApplicationSettingsFile=" + FileSystem.ApplicationSettingsFile);
                Log.WriteDebugMessage("UserSettingsFile=" + FileSystem.UserSettingsFile);
                Log.WriteDebugMessage("DebugFolder=" + FileSystem.DebugFolder);
                Log.WriteDebugMessage("LogsFolder=" + FileSystem.LogsFolder);
                Log.WriteDebugMessage("CommandFile=" + FileSystem.CommandFile);
                Log.WriteDebugMessage("ScreenshotsFolder=" + FileSystem.ScreenshotsFolder);
                Log.WriteDebugMessage("ScreenshotsFile=" + FileSystem.ScreenshotsFile);
                Log.WriteDebugMessage("TriggersFile=" + FileSystem.TriggersFile);
                Log.WriteDebugMessage("ScreensFile=" + FileSystem.ScreensFile);
                Log.WriteDebugMessage("RegionsFile=" + FileSystem.RegionsFile);
                Log.WriteDebugMessage("EditorsFile=" + FileSystem.EditorsFile);
                Log.WriteDebugMessage("TagsFile = " + FileSystem.TagsFile);

                Log.WriteDebugMessage("It looks like I successfully parsed your \"" + FileSystem.ConfigFile + "\" file.");
                Log.WriteDebugMessage("I'm now going to attempt to load your personal settings and any screenshots you have taken.");

                Log.WriteMessage("Initializing screen capture");
                _screenCapture = new ScreenCapture();

                Log.WriteMessage("Initializing image format collection");
                _imageFormatCollection = new ImageFormatCollection();

                Log.WriteMessage("Initializing editor collection");

                if (!_formEditor.EditorCollection.LoadXmlFileAndAddEditors())
                {
                    _screenCapture.ApplicationError = true;
                }

                Log.WriteDebugMessage("Number of editors loaded = " + _formEditor.EditorCollection.Count);

                Log.WriteMessage("Initializing trigger collection");

                if (!_formTrigger.TriggerCollection.LoadXmlFileAndAddTriggers())
                {
                    _screenCapture.ApplicationError = true;
                }

                Log.WriteDebugMessage("Number of triggers loaded = " + _formTrigger.TriggerCollection.Count);

                Log.WriteMessage("Initializing region collection");

                if (!_formRegion.RegionCollection.LoadXmlFileAndAddRegions(_imageFormatCollection))
                {
                    _screenCapture.ApplicationError = true;
                }

                // Add regions to the Screen form so we can select them as a source.
                _formScreen.RegionCollection = _formRegion.RegionCollection;

                Log.WriteDebugMessage("Number of regions loaded = " + _formRegion.RegionCollection.Count);

                Log.WriteMessage("Initializing screen collection");

                if (!_formScreen.ScreenCollection.LoadXmlFileAndAddScreens(_imageFormatCollection))
                {
                    _screenCapture.ApplicationError = true;
                }

                Log.WriteDebugMessage("Number of screens loaded = " + _formScreen.ScreenCollection.Count);

                Log.WriteMessage("Initializing tag collection");

                if (!_formMacroTag.MacroTagCollection.LoadXmlFileAndAddTags())
                {
                    _screenCapture.ApplicationError = true;
                }

                Log.WriteDebugMessage("Number of tags loaded = " + _formMacroTag.MacroTagCollection.Count);

                Log.WriteMessage("Initializing schedule collection");

                if (!_formSchedule.ScheduleCollection.LoadXmlFileAndAddSchedules())
                {
                    _screenCapture.ApplicationError = true;
                }

                Log.WriteDebugMessage("Number of schedules loaded = " + _formSchedule.ScheduleCollection.Count);

                Log.WriteMessage("Building screens module");
                BuildScreensModule();

                Log.WriteMessage("Building editors module");
                BuildEditorsModule();

                Log.WriteMessage("Building triggers module");
                BuildTriggersModule();

                Log.WriteMessage("Building regions module");
                BuildRegionsModule();

                Log.WriteMessage("Building tags module");
                BuildMacroTagsModule();

                Log.WriteMessage("Building schedules module");
                BuildSchedulesModule();

                Log.WriteMessage("Building screenshot preview context menu");
                BuildScreenshotPreviewContextualMenu();

                Log.WriteMessage("Building view tab pages");
                BuildViewTabPages();

                Log.WriteMessage("Initializing screenshot collection");
                _screenshotCollection = new ScreenshotCollection(_imageFormatCollection, _formScreen.ScreenCollection);

                _screenshotCollection.LoadXmlFile();

                int screenCaptureInterval = Convert.ToInt32(Settings.User.GetByKey("ScreenCaptureInterval", DefaultSettings.ScreenCaptureInterval).Value);
                Log.WriteDebugMessage("ScreenCaptureInterval = " + screenCaptureInterval);

                if (screenCaptureInterval == 0)
                {
                    screenCaptureInterval = DefaultSettings.ScreenCaptureInterval;
                    Log.WriteDebugMessage("WARNING: Screen capture interval was found to be 0 so 60,000 milliseconds (or 1 minute) is being used as the default value");
                }

                Log.WriteDebugMessage("Assigning screen capture interval value to its appropriate hour, minute, second, and millisecond variables");

                decimal screenCaptureIntervalHours = Convert.ToDecimal(TimeSpan.FromMilliseconds(Convert.ToDouble(screenCaptureInterval)).Hours);
                Log.WriteDebugMessage("Hours = " + screenCaptureIntervalHours);

                decimal screenCaptureIntervalMinutes = Convert.ToDecimal(TimeSpan.FromMilliseconds(Convert.ToDouble(screenCaptureInterval)).Minutes);
                Log.WriteDebugMessage("Minutes = " + screenCaptureIntervalMinutes);

                decimal screenCaptureIntervalSeconds = Convert.ToDecimal(TimeSpan.FromMilliseconds(Convert.ToDouble(screenCaptureInterval)).Seconds);
                Log.WriteDebugMessage("Seconds = " + screenCaptureIntervalSeconds);

                decimal screenCaptureIntervalMilliseconds = Convert.ToDecimal(TimeSpan.FromMilliseconds(Convert.ToDouble(screenCaptureInterval)).Milliseconds);
                Log.WriteDebugMessage("Milliseconds = " + screenCaptureIntervalMilliseconds);

                numericUpDownHoursInterval.Value        = screenCaptureIntervalHours;
                numericUpDownMinutesInterval.Value      = screenCaptureIntervalMinutes;
                numericUpDownSecondsInterval.Value      = screenCaptureIntervalSeconds;
                numericUpDownMillisecondsInterval.Value = screenCaptureIntervalMilliseconds;

                numericUpDownCaptureLimit.Value = Convert.ToInt32(Settings.User.GetByKey("CaptureLimit", DefaultSettings.CaptureLimit).Value);
                Log.WriteDebugMessage("CaptureLimit = " + numericUpDownCaptureLimit.Value);

                checkBoxCaptureLimit.Checked = Convert.ToBoolean(Settings.User.GetByKey("CaptureLimitCheck", DefaultSettings.CaptureLimitCheck).Value);
                Log.WriteDebugMessage("CaptureLimitCheck = " + checkBoxCaptureLimit.Checked);

                checkBoxInitialScreenshot.Checked = Convert.ToBoolean(Settings.User.GetByKey("TakeInitialScreenshot", DefaultSettings.TakeInitialScreenshot).Value);
                Log.WriteDebugMessage("TakeInitialScreenshot = " + checkBoxInitialScreenshot.Checked);

                notifyIcon.Visible = Convert.ToBoolean(Settings.User.GetByKey("ShowSystemTrayIcon", DefaultSettings.ShowSystemTrayIcon).Value);
                Log.WriteDebugMessage("ShowSystemTrayIcon = " + notifyIcon.Visible);

                comboBoxScreenshotLabel.Text = Settings.User.GetByKey("ScreenshotLabel", DefaultSettings.ScreenshotLabel).Value.ToString();
                Log.WriteDebugMessage("ScreenshotLabel = " + comboBoxScreenshotLabel.Text);

                checkBoxScreenshotLabel.Checked = Convert.ToBoolean(Settings.User.GetByKey("ApplyScreenshotLabel", DefaultSettings.ApplyScreenshotLabel).Value);

                // Active Window Title
                checkBoxActiveWindowTitle.Checked = Convert.ToBoolean(Settings.User.GetByKey("ActiveWindowTitleCaptureCheck", DefaultSettings.ActiveWindowTitleCaptureCheck).Value);
                textBoxActiveWindowTitle.Text     = Settings.User.GetByKey("ActiveWindowTitleCaptureText", DefaultSettings.ActiveWindowTitleCaptureText).Value.ToString();

                if (checkBoxActiveWindowTitle.Checked)
                {
                    textBoxActiveWindowTitle.Enabled          = true;
                    radioButtonCaseSensitiveMatch.Enabled     = true;
                    radioButtonCaseInsensitiveMatch.Enabled   = true;
                    radioButtonRegularExpressionMatch.Enabled = true;
                }
                else
                {
                    textBoxActiveWindowTitle.Enabled          = false;
                    radioButtonCaseSensitiveMatch.Enabled     = false;
                    radioButtonCaseInsensitiveMatch.Enabled   = false;
                    radioButtonRegularExpressionMatch.Enabled = false;
                }

                radioButtonCaseSensitiveMatch.Checked     = false;
                radioButtonCaseInsensitiveMatch.Checked   = false;
                radioButtonRegularExpressionMatch.Checked = false;

                int activeWindowTitleMatchType = Convert.ToInt32(Settings.User.GetByKey("ActiveWindowTitleMatchType", DefaultSettings.ActiveWindowTitleMatchType).Value);

                switch (activeWindowTitleMatchType)
                {
                case 1:
                    radioButtonCaseSensitiveMatch.Checked = true;
                    break;

                case 2:
                    radioButtonCaseInsensitiveMatch.Checked = true;
                    break;

                case 3:
                    radioButtonRegularExpressionMatch.Checked = true;
                    break;
                }


                // Application Focus
                RefreshApplicationFocusList();

                // Region Select / Auto Save
                textBoxAutoSaveFolder.Text = Settings.User.GetByKey("AutoSaveFolder", DefaultSettings.AutoSaveFolder).Value.ToString();
                textBoxAutoSaveMacro.Text  = Settings.User.GetByKey("AutoSaveMacro", DefaultSettings.AutoSaveMacro).Value.ToString();

                EnableStartCapture();

                CaptureLimitCheck();

                Log.WriteDebugMessage("Settings loaded");
            }
            catch (Exception ex)
            {
                _screenCapture.ApplicationError = true;
                Log.WriteExceptionMessage("FormMain-Settings::LoadSettings", ex);
            }
        }
Ejemplo n.º 7
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);
            }
        }
Ejemplo n.º 8
0
        private void CheckAndCreateFiles(Security security, ScreenCapture screenCapture, Log log)
        {
            if (string.IsNullOrEmpty(FileSystem.CommandFile))
            {
                FileSystem.CommandFile = FileSystem.DefaultCommandFile;

                FileSystem.AppendToFile(FileSystem.ConfigFile, "\nCommandFile=" + FileSystem.DefaultCommandFile);

                if (!FileSystem.FileExists(FileSystem.DefaultCommandFile))
                {
                    FileSystem.CreateFile(FileSystem.DefaultCommandFile);
                }
            }

            if (string.IsNullOrEmpty(FileSystem.ApplicationSettingsFile))
            {
                FileSystem.ApplicationSettingsFile = FileSystem.DefaultApplicationSettingsFile;

                FileSystem.AppendToFile(FileSystem.ConfigFile, "\nApplicationSettingsFile=" + FileSystem.DefaultApplicationSettingsFile);

                if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder))
                {
                    FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder);
                }
            }

            if (string.IsNullOrEmpty(FileSystem.SmtpSettingsFile))
            {
                FileSystem.SmtpSettingsFile = FileSystem.DefaultSmtpSettingsFile;

                FileSystem.AppendToFile(FileSystem.ConfigFile, "\nSMTPSettingsFile=" + FileSystem.DefaultSmtpSettingsFile);

                if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder))
                {
                    FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder);
                }
            }

            if (string.IsNullOrEmpty(FileSystem.SftpSettingsFile))
            {
                FileSystem.SftpSettingsFile = FileSystem.DefaultSftpSettingsFile;

                FileSystem.AppendToFile(FileSystem.ConfigFile, "\nSFTPSettingsFile=" + FileSystem.DefaultSftpSettingsFile);

                if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder))
                {
                    FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder);
                }
            }

            if (string.IsNullOrEmpty(FileSystem.UserSettingsFile))
            {
                FileSystem.UserSettingsFile = FileSystem.DefaultUserSettingsFile;

                FileSystem.AppendToFile(FileSystem.ConfigFile, "\nUserSettingsFile=" + FileSystem.DefaultUserSettingsFile);

                if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder))
                {
                    FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder);
                }
            }

            Settings.User.Load(Settings, FileSystem);

            Settings.SMTP.Load(Settings, FileSystem);

            Settings.SFTP.Load(Settings, FileSystem);

            Settings.VersionManager.OldApplicationSettings = Settings.Application.Clone();

            Settings.VersionManager.OldUserSettings = Settings.User.Clone();

            Settings.UpgradeApplicationSettings(Settings.Application, FileSystem);

            Settings.UpgradeUserSettings(Settings.User, screenCapture, security, FileSystem);

            Settings.UpgradeSmtpSettings(Settings.SMTP, FileSystem);

            Settings.UpgradeSftpSettings(Settings.SFTP, FileSystem);

            if (string.IsNullOrEmpty(FileSystem.ScreenshotsFile))
            {
                ImageFormatCollection imageFormatCollection = new ImageFormatCollection();
                ScreenCollection      screenCollection      = new ScreenCollection();

                ScreenshotCollection screenshotCollection = new ScreenshotCollection(imageFormatCollection, screenCollection, screenCapture, this, FileSystem, log);
                screenshotCollection.SaveToXmlFile(this);
            }

            if (string.IsNullOrEmpty(FileSystem.EditorsFile))
            {
                // Loading the editor collection will automatically create the default editors and add them to the collection.
                EditorCollection editorCollection = new EditorCollection();
                editorCollection.LoadXmlFileAndAddEditors(this, FileSystem, log);
            }

            if (string.IsNullOrEmpty(FileSystem.RegionsFile))
            {
                RegionCollection regionCollection = new RegionCollection();
                regionCollection.SaveToXmlFile(Settings, FileSystem, log);
            }

            if (string.IsNullOrEmpty(FileSystem.ScreensFile))
            {
                // Loading the screen collection will automatically create the available screens and add them to the collection.
                ScreenCollection screenCollection = new ScreenCollection();
                screenCollection.LoadXmlFileAndAddScreens(new ImageFormatCollection(), this, MacroParser, screenCapture, FileSystem, log);
            }

            if (string.IsNullOrEmpty(FileSystem.TriggersFile))
            {
                // Loading triggers will automatically create the default triggers and add them to the collection.
                TriggerCollection triggerCollection = new TriggerCollection();
                triggerCollection.LoadXmlFileAndAddTriggers(this, FileSystem, log);
            }

            if (string.IsNullOrEmpty(FileSystem.TagsFile))
            {
                // Loading tags will automatically create the default tags and add them to the collection.
                MacroTagCollection tagCollection = new MacroTagCollection();
                tagCollection.LoadXmlFileAndAddTags(this, MacroParser, FileSystem, log);
            }

            if (string.IsNullOrEmpty(FileSystem.SchedulesFile))
            {
                // Loading schedules will automatically create the default schedules and add them to the collection.
                ScheduleCollection scheduleCollection = new ScheduleCollection();
                scheduleCollection.LoadXmlFileAndAddSchedules(this, FileSystem, log);
            }
        }
Ejemplo n.º 9
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);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Saves the captured bitmap image as a screenshot to an image file.
        /// </summary>
        /// <param name="security">The security class.</param>
        /// <param name="jpegQuality">The JPEG quality setting for JPEG images being saved.</param>
        /// <param name="screenshot">The screenshot to save.</param>
        /// <param name="screenshotCollection">A collection of screenshot objects.</param>
        /// <returns>A boolean to determine if we successfully saved the screenshot.</returns>
        public int SaveScreenshot(Security security, int jpegQuality, Screenshot screenshot, ScreenshotCollection screenshotCollection)
        {
            int returnFlag = 0;

            try
            {
                int filepathLengthLimit = Convert.ToInt32(_config.Settings.Application.GetByKey("FilepathLengthLimit", _config.Settings.DefaultSettings.FilepathLengthLimit).Value);

                if (!string.IsNullOrEmpty(screenshot.FilePath))
                {
                    if (screenshot.FilePath.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");
                        screenshot.FilePath = screenshot.FilePath.Substring(0, filepathLengthLimit);
                    }

                    // This is a normal path used in Windows (such as "C:\screenshots\").
                    if (!screenshot.FilePath.StartsWith(_fileSystem.PathDelimiter))
                    {
                        if (_fileSystem.DriveReady(screenshot.FilePath))
                        {
                            // The low disk mode we want to use (either check by percentage (0) or check the number of available bytes (1)).
                            int lowDiskMode = Convert.ToInt32(_config.Settings.Application.GetByKey("LowDiskMode", _config.Settings.DefaultSettings.LowDiskMode).Value);

                            // Low disk space threshold by percentage.
                            int    lowDiskPercentageThreshold = Convert.ToInt32(_config.Settings.Application.GetByKey("LowDiskPercentageThreshold", _config.Settings.DefaultSettings.LowDiskPercentageThreshold).Value);
                            double freeDiskSpacePercentage    = _fileSystem.FreeDiskSpacePercentage(screenshot.FilePath);

                            // Low disk space threshold in bytes.
                            long lowDiskBytesThreshold = Convert.ToInt64(_config.Settings.Application.GetByKey("LowDiskBytesThreshold", _config.Settings.DefaultSettings.LowDiskBytesThreshold).Value);
                            long freeDiskSpaceBytes    = _fileSystem.FreeDiskSpace(screenshot.FilePath);

                            _log.WriteDebugMessage("Percentage of free disk space on drive for \"" + screenshot.FilePath + "\" is " + (int)freeDiskSpacePercentage + "% and low disk percentage threshold is set to " + lowDiskPercentageThreshold + "%");
                            _log.WriteDebugMessage("Bytes of free disk space on drive for \"" + screenshot.FilePath + "\" is " + freeDiskSpaceBytes + " and low disk bytes threshold is set to " + lowDiskBytesThreshold);

                            // Check low disk space by percentage.
                            if (lowDiskMode == 0)
                            {
                                if (freeDiskSpacePercentage < lowDiskPercentageThreshold)
                                {
                                    return(NotEnoughDiskSpace(screenshot, returnFlag, freeDiskSpacePercentage, lowDiskPercentageThreshold, freeDiskSpaceBytes, lowDiskBytesThreshold));
                                }
                            }

                            // Check low disk space in bytes.
                            if (lowDiskMode == 1)
                            {
                                if (freeDiskSpaceBytes < lowDiskBytesThreshold)
                                {
                                    return(NotEnoughDiskSpace(screenshot, returnFlag, freeDiskSpacePercentage, lowDiskPercentageThreshold, freeDiskSpaceBytes, lowDiskBytesThreshold));
                                }
                            }

                            return(SaveToFile(security, jpegQuality, screenshot, screenshotCollection));
                        }
                        else
                        {
                            // Drive isn't ready so log an error message.
                            _log.WriteErrorMessage($"Unable to save screenshot for \"{screenshot.FilePath}\" because the drive is not found or not ready");

                            return(returnFlag | (int)ScreenSavingErrorLevels.DriveNotReady);
                        }
                    }
                    else
                    {
                        // This is a UNC network share path (such as "\\SERVER\screenshots\").
                        return(SaveToFile(security, jpegQuality, screenshot, screenshotCollection));
                    }
                }

                return(returnFlag & (int)ScreenSavingErrorLevels.None);
            }
            catch (PathTooLongException ex)
            {
                _log.WriteErrorMessage($"The path is too long. I see the path is \"{screenshot.FilePath}\" 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(returnFlag | (int)ScreenSavingErrorLevels.PathLengthExceeded);
            }
            catch (Exception ex)
            {
                _log.WriteExceptionMessage("ScreenCapture::SaveScreenshot", ex);

                return(returnFlag | (int)ScreenSavingErrorLevels.ExceptionCaught);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Saves the captured bitmap image as a screenshot to an image file.
        /// </summary>
        /// <param name="jpegQuality">The JPEG quality setting for JPEG images being saved.</param>
        /// <param name="screenshot">The screenshot to save.</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(int jpegQuality, Screenshot screenshot, ScreenshotCollection screenshotCollection)
        {
            try
            {
                int filepathLengthLimit = Convert.ToInt32(Settings.Application.GetByKey("FilepathLengthLimit", DefaultSettings.FilepathLengthLimit).Value);

                if (!string.IsNullOrEmpty(screenshot.Path))
                {
                    if (screenshot.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");
                        screenshot.Path = screenshot.Path.Substring(0, filepathLengthLimit);
                    }

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

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

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

                            if (freeDiskSpacePercentage > lowDiskSpacePercentageThreshold)
                            {
                                AddScreenshotAndSaveToFile(jpegQuality, screenshot, screenshotCollection);
                            }
                            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 {screenshot.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 \"{screenshot.Path}\" because the drive is not found or not ready");
                        }
                    }
                    else
                    {
                        // This is a UNC network share path (such as "\\SERVER\screenshots\").
                        AddScreenshotAndSaveToFile(jpegQuality, screenshot, screenshotCollection);
                    }
                }

                return(true);
            }
            catch (System.IO.PathTooLongException ex)
            {
                Log.WriteErrorMessage($"The path is too long. I see the path is \"{screenshot.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);
            }
        }
Ejemplo n.º 12
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");
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Loads the user's saved settings.
        /// </summary>
        private void LoadSettings()
        {
            try
            {
                _macroParser = new MacroParser(_config.Settings);

                _log.WriteMessage("*** Welcome to " + _config.Settings.ApplicationName + " " + _config.Settings.ApplicationVersion + " (\"" + _config.Settings.ApplicationCodename + "\") ***");
                _log.WriteMessage("Starting application");
                _log.WriteDebugMessage("At this point the application should be able to run normally");
                _log.WriteDebugMessage("but it would be a good idea to check what we found in your autoscreen.conf file");
                _log.WriteDebugMessage("Your autoscreen.conf file is \"" + _fileSystem.ConfigFile + "\"");
                _log.WriteDebugMessage("The name and location of it can be changed with the -config command line argument:");
                _log.WriteDebugMessage("autoscreen.exe -config=C:\\MyAutoScreenCapture.conf");
                _log.WriteDebugMessage("Checking what we loaded from your autoscreen.conf file ...");
                _log.WriteDebugMessage("ApplicationSettingsFile=" + _fileSystem.ApplicationSettingsFile);
                _log.WriteDebugMessage("UserSettingsFile=" + _fileSystem.UserSettingsFile);
                _log.WriteDebugMessage("ErrorsFolder=" + _fileSystem.ErrorsFolder);
                _log.WriteDebugMessage("LogsFolder=" + _fileSystem.LogsFolder);
                _log.WriteDebugMessage("CommandFile=" + _fileSystem.CommandFile);
                _log.WriteDebugMessage("ScreenshotsFolder=" + _fileSystem.ScreenshotsFolder);
                _log.WriteDebugMessage("ScreenshotsFile=" + _fileSystem.ScreenshotsFile);
                _log.WriteDebugMessage("TriggersFile=" + _fileSystem.TriggersFile);
                _log.WriteDebugMessage("ScreensFile=" + _fileSystem.ScreensFile);
                _log.WriteDebugMessage("RegionsFile=" + _fileSystem.RegionsFile);
                _log.WriteDebugMessage("EditorsFile=" + _fileSystem.EditorsFile);
                _log.WriteDebugMessage("MacroTagsFile=" + _fileSystem.MacroTagsFile);
                _log.WriteDebugMessage("FilenamePattern=" + _fileSystem.FilenamePattern);
                _log.WriteDebugMessage("ImageFormat=" + ScreenCapture.ImageFormat);

                _log.WriteDebugMessage("It looks like the application successfully parsed your \"" + _fileSystem.ConfigFile + "\" file");

                _log.WriteDebugMessage("Checking for a user-defined screenshots folder path in user settings and if it differs from the path set by autoscreen.conf");

                // Let's see if the user has their own screenshots folder they would like to use. Check user settings.
                // If they have defined a screenshots folder in user settings then use that folder path otherwise keep using the path from the config file.
                Setting screenshotsFolderDefinedByUser = _config.Settings.User.GetByKey("ScreenshotsFolder", _fileSystem.ScreenshotsFolder, createKeyIfNotFound: false);

                // Set the screenshots folder path to be the user-defined screenshots folder path if it's different from the path used by the configuration file.
                if (screenshotsFolderDefinedByUser != null && !screenshotsFolderDefinedByUser.Value.ToString().Equals(_fileSystem.ScreenshotsFolder))
                {
                    _fileSystem.ScreenshotsFolder = screenshotsFolderDefinedByUser.Value.ToString();

                    _log.WriteDebugMessage("WARNING! A user-defined screenshots folder path was found in user settings and this path is different from what was set in the autoscreen.conf file so the application will be using this path instead!");
                    _log.WriteDebugMessage("The screenshots folder path that will be used is \"" + _fileSystem.ScreenshotsFolder + "\"");
                }
                else
                {
                    _log.WriteDebugMessage("No difference in folder path found. Screenshots folder path from autoscreen.conf file will be used (\"" + _fileSystem.ScreenshotsFolder + "\")");
                }

                // Let's see if the user has their own filename pattern they would like to use. Check user settings.
                // If they have defined a filename pattern in user settings then use that filename pattern otherwise keep using the filename pattern from the config file.
                Setting filenamePatternDefinedByUser = _config.Settings.User.GetByKey("FilenamePattern", _fileSystem.FilenamePattern, createKeyIfNotFound: false);

                if (filenamePatternDefinedByUser != null && !filenamePatternDefinedByUser.Value.ToString().Equals(_fileSystem.FilenamePattern))
                {
                    _fileSystem.FilenamePattern = filenamePatternDefinedByUser.Value.ToString();

                    _log.WriteDebugMessage("WARNING! A user-defined filename pattern was found in user settings and it is different from what was set in the autoscreen.conf file so the application will be using the user-defined filename pattern instead!");
                    _log.WriteDebugMessage("The filename pattern that will be used is \"" + _fileSystem.FilenamePattern + "\"");
                }
                else
                {
                    _log.WriteDebugMessage("No difference in filename pattern found. Filename pattern in autoscreen.conf file will be used (\"" + _fileSystem.FilenamePattern + "\")");
                }

                _log.WriteDebugMessage("Initializing screen capture");
                _screenCapture = new ScreenCapture(_config, _fileSystem, _log);

                _log.WriteDebugMessage("Initializing image format collection");
                _imageFormatCollection = new ImageFormatCollection();

                _log.WriteDebugMessage("Initializing forms");
                _formAbout = new FormAbout();
                _formHelp  = new FormHelp();
                _formDynamicRegexValidator = new FormDynamicRegexValidator();
                _formScreenshotMetadata    = new FormScreenshotMetadata();
                _formLabelSwitcher         = new FormLabelSwitcher(_config, _fileSystem);
                _formMacroTag             = new FormMacroTag(_macroParser);
                _formRegion               = new FormRegion(_screenCapture, _macroParser, _fileSystem, _config, _log);
                _formScreen               = new FormScreen(_screenCapture, _macroParser, _fileSystem, _config, _log);
                _formEditor               = new FormEditor(_config, _fileSystem);
                _formEmailSettings        = new FormEmailSettings(_config, _fileSystem, _log);
                _formFileTransferSettings = new FormFileTransferSettings(_config, _fileSystem, _log);
                _formRegionSelectOptions  = new FormRegionSelectOptions(_config, _fileSystem, _imageFormatCollection);
                _formCaptureNowOptions    = new FormCaptureNowOptions(_config, _fileSystem);
                _formSchedule             = new FormSchedule(_formScreen, _formRegion);
                _formTrigger              = new FormTrigger(_fileSystem);
                _formEnterPassphrase      = new FormEnterPassphrase(_security, _config, _log);
                _formScreenCaptureStatus  = new FormScreenCaptureStatus();

                // Event Handlers
                _formSchedule.StartSchedule += _formSchedule_StartSchedule;
                _formSchedule.StopSchedule  += _formSchedule_StopSchedule;
                _formScreenCaptureStatus.buttonStartStopScreenCapture.Click += _formLabelSwitcher_buttonStartStopScreenCapture_Click; // Screen Capture Status
                _formLabelSwitcher.buttonStartStopScreenCapture.Click       += _formLabelSwitcher_buttonStartStopScreenCapture_Click; // Screen Capture Status With Label Switcher

                ToolTip toolTipButtonStartStopScreenCaptureScreenCaptureStatus = new ToolTip();
                toolTipButtonStartStopScreenCaptureScreenCaptureStatus.SetToolTip(_formScreenCaptureStatus.buttonStartStopScreenCapture, "Start/Stop Screen Capture");

                ToolTip toolTipButtonStartStopScreenCaptureLabelSwitcher = new ToolTip();
                toolTipButtonStartStopScreenCaptureLabelSwitcher.SetToolTip(_formLabelSwitcher.buttonStartStopScreenCapture, "Start/Stop Screen Capture");

                _log.WriteDebugMessage("Initializing email manager");
                _emailManager = new EmailManager(_log);

                if (_config.CleanStartup)
                {
                    _log.WriteDebugMessage("CleanStartup detected so we will not load XML data");
                }
                else
                {
                    _log.WriteDebugMessage("Initializing editor collection");

                    if (!_formEditor.EditorCollection.LoadXmlFileAndAddEditors(_config, _fileSystem, _log))
                    {
                        _screenCapture.ApplicationError = true;
                    }

                    _log.WriteDebugMessage("Number of editors loaded = " + _formEditor.EditorCollection.Count);

                    _log.WriteDebugMessage("Initializing trigger collection");

                    if (!_formTrigger.TriggerCollection.LoadXmlFileAndAddTriggers(_config, _fileSystem, _log))
                    {
                        _screenCapture.ApplicationError = true;
                    }

                    _log.WriteDebugMessage("Number of triggers loaded = " + _formTrigger.TriggerCollection.Count);

                    _log.WriteDebugMessage("Initializing region collection");

                    if (!_formRegion.RegionCollection.LoadXmlFileAndAddRegions(_imageFormatCollection, _config, _fileSystem, _log))
                    {
                        _screenCapture.ApplicationError = true;
                    }

                    // Add regions to the Screen form so we can select them as a source.
                    _formScreen.RegionCollection = _formRegion.RegionCollection;
                    _log.WriteDebugMessage("Number of regions loaded = " + _formRegion.RegionCollection.Count);

                    _log.WriteDebugMessage("Initializing screen collection");

                    if (!_formScreen.ScreenCollection.LoadXmlFileAndAddScreens(_imageFormatCollection, _config, _macroParser, _fileSystem, _log))
                    {
                        _screenCapture.ApplicationError = true;
                    }

                    _log.WriteDebugMessage("Number of screens loaded = " + _formScreen.ScreenCollection.Count);

                    _log.WriteDebugMessage("Initializing tag collection");

                    if (!_formMacroTag.MacroTagCollection.LoadXmlFileAndAddTags(_config, _macroParser, _fileSystem, _log))
                    {
                        _screenCapture.ApplicationError = true;
                    }

                    _log.WriteDebugMessage("Number of tags loaded = " + _formMacroTag.MacroTagCollection.Count);

                    _log.WriteDebugMessage("Initializing schedule collection");

                    if (!_formSchedule.ScheduleCollection.LoadXmlFileAndAddSchedules(_config, _fileSystem, _log))
                    {
                        _screenCapture.ApplicationError = true;
                    }

                    _log.WriteDebugMessage("Number of schedules loaded = " + _formSchedule.ScheduleCollection.Count);
                }

                _log.WriteDebugMessage("Building screens module");
                BuildScreensModule();

                _log.WriteDebugMessage("Building editors module");
                BuildEditorsModule();

                _log.WriteDebugMessage("Building triggers module");
                BuildTriggersModule();

                _log.WriteDebugMessage("Building regions module");
                BuildRegionsModule();

                _log.WriteDebugMessage("Building tags module");
                BuildMacroTagsModule();

                _log.WriteDebugMessage("Building schedules module");
                BuildSchedulesModule();

                _log.WriteDebugMessage("Building screenshot preview context menu");
                BuildScreenshotPreviewContextualMenu();

                // Add the ScheduleTimer_Tick event to each schedule.
                // This ensures that each schedule can run on its own interval when taking screenshots
                // and acts independently from the main timer (depending on the logic chosen for the schedule).
                foreach (Schedule schedule in _formSchedule.ScheduleCollection)
                {
                    schedule.Timer.Tag      = schedule;
                    schedule.Timer.Interval = schedule.ScreenCaptureInterval;
                    schedule.Timer.Enabled  = false;
                    schedule.Timer.Tick    += ScheduleTimer_Tick;
                }

                // Set the tab page we want to look at. By default it's going to be index 0 for the "Dashboard" tab page.
                tabControlViews.SelectedIndex = Convert.ToInt32(_config.Settings.User.GetByKey("SelectedTabPageIndex", _config.Settings.DefaultSettings.SelectedTabPageIndex).Value);

                if (tabControlViews.SelectedIndex < 0)
                {
                    tabControlViews.SelectedIndex = 0;
                }

                // Set the module we want to look at.
                tabControlModules.SelectedIndex = Convert.ToInt32(_config.Settings.User.GetByKey("SelectedModuleIndex", _config.Settings.DefaultSettings.SelectedModuleIndex).Value);

                // Preview
                _preview = Convert.ToBoolean(_config.Settings.User.GetByKey("Preview", _config.Settings.DefaultSettings.Preview).Value);
                _log.WriteDebugMessage("Preview = " + _preview.ToString());

                _dashboardGroupBoxSize = Convert.ToInt32(_config.Settings.User.GetByKey("DashboardGroupBoxSize", _config.Settings.DefaultSettings.DashboardGroupBoxSize).Value);
                _log.WriteDebugMessage("DashboardGroupBoxSize = " + _dashboardGroupBoxSize);
                _log.WriteDebugMessage("Building view tab pages");
                BuildViewTabPages();

                // Screenshots Collection
                _log.WriteDebugMessage("Initializing screenshot collection");
                _screenshotCollection = new ScreenshotCollection(_imageFormatCollection, _formScreen.ScreenCollection, _screenCapture, _config, _fileSystem, _log, _security);
                _screenshotCollection.LoadXmlFile(_config);

                // Encryptor / Decryptor
                _formEncryptorDecryptor = new FormEncryptorDecryptor(_log, _config, _security, _fileSystem, _screenshotCollection);
                _formEncryptorDecryptor.screenshotsEncrypted += ScreenshotsEncrypted;
                _formEncryptorDecryptor.screenshotsDecrypted += ScreenshotsDecrypted;

                // Region Select Command Deck
                _formRegionSelectCommandDeck = new FormRegionSelectCommandDeck();

                int screenCaptureInterval = Convert.ToInt32(_config.Settings.User.GetByKey("ScreenCaptureInterval", _config.Settings.DefaultSettings.ScreenCaptureInterval).Value);
                _log.WriteDebugMessage("ScreenCaptureInterval = " + screenCaptureInterval);

                if (screenCaptureInterval == 0)
                {
                    screenCaptureInterval = _config.Settings.DefaultSettings.ScreenCaptureInterval;
                    _log.WriteDebugMessage("WARNING: Screen capture interval was found to be 0 so 60,000 milliseconds (or 1 minute) is being used as the default value");
                }

                // Set the interval for "Special Schedule"
                _formSchedule.ScheduleCollection.SpecialScheduleScreenCaptureInterval = screenCaptureInterval;

                _log.WriteDebugMessage("Assigning screen capture interval value to its appropriate hour, minute, second, and millisecond variables");

                decimal screenCaptureIntervalHours = Convert.ToDecimal(TimeSpan.FromMilliseconds(Convert.ToDouble(screenCaptureInterval)).Hours);
                _log.WriteDebugMessage("Hours = " + screenCaptureIntervalHours);

                decimal screenCaptureIntervalMinutes = Convert.ToDecimal(TimeSpan.FromMilliseconds(Convert.ToDouble(screenCaptureInterval)).Minutes);
                _log.WriteDebugMessage("Minutes = " + screenCaptureIntervalMinutes);

                decimal screenCaptureIntervalSeconds = Convert.ToDecimal(TimeSpan.FromMilliseconds(Convert.ToDouble(screenCaptureInterval)).Seconds);
                _log.WriteDebugMessage("Seconds = " + screenCaptureIntervalSeconds);

                // Setup
                _formSetup = new FormSetup(_log, _security, _config, _fileSystem, _screenCapture, _formLabelSwitcher, _formScreen, _formRegion, _formMacroTag.MacroTagCollection, _macroParser, _screenshotCollection);

                _formSetup.numericUpDownHoursInterval.Value   = screenCaptureIntervalHours;
                _formSetup.numericUpDownMinutesInterval.Value = screenCaptureIntervalMinutes;
                _formSetup.numericUpDownSecondsInterval.Value = screenCaptureIntervalSeconds;

                // Optimize Screen Capture
                _formSetup.checkBoxOptimizeScreenCapture.Checked = Convert.ToBoolean(_config.Settings.User.GetByKey("OptimizeScreenCapture", _config.Settings.DefaultSettings.OptimizeScreenCapture).Value);
                _formSetup.trackBarImageDiffTolerance.Value      = Convert.ToInt32(_config.Settings.User.GetByKey("ImageDiffTolerance", _config.Settings.DefaultSettings.ImageDiffTolerance).Value);

                _formSetup.numericUpDownCaptureLimit.Value = Convert.ToInt32(_config.Settings.User.GetByKey("CaptureLimit", _config.Settings.DefaultSettings.CaptureLimit).Value);
                _log.WriteDebugMessage("CaptureLimit = " + _formSetup.numericUpDownCaptureLimit.Value);

                _formSetup.checkBoxCaptureLimit.Checked = Convert.ToBoolean(_config.Settings.User.GetByKey("CaptureLimitCheck", _config.Settings.DefaultSettings.CaptureLimitCheck).Value);
                _log.WriteDebugMessage("CaptureLimitCheck = " + _formSetup.checkBoxCaptureLimit.Checked);

                _formSetup.checkBoxInitialScreenshot.Checked = Convert.ToBoolean(_config.Settings.User.GetByKey("TakeInitialScreenshot", _config.Settings.DefaultSettings.TakeInitialScreenshot).Value);
                _log.WriteDebugMessage("TakeInitialScreenshot = " + _formSetup.checkBoxInitialScreenshot.Checked);

                // Active Window Title
                _formSetup.checkBoxActiveWindowTitleComparisonCheck.Checked        = Convert.ToBoolean(_config.Settings.User.GetByKey("ActiveWindowTitleCaptureCheck", _config.Settings.DefaultSettings.ActiveWindowTitleCaptureCheck).Value);
                _formSetup.checkBoxActiveWindowTitleComparisonCheckReverse.Checked = Convert.ToBoolean(_config.Settings.User.GetByKey("ActiveWindowTitleNoMatchCheck", _config.Settings.DefaultSettings.ActiveWindowTitleNoMatchCheck).Value);
                _formSetup.textBoxActiveWindowTitle.Text     = _config.Settings.User.GetByKey("ActiveWindowTitleCaptureText", _config.Settings.DefaultSettings.ActiveWindowTitleCaptureText).Value.ToString();
                _formSetup.textBoxActiveWindowTitleTest.Text = _config.Settings.User.GetByKey("ActiveWindowTitleSampleText", _config.Settings.DefaultSettings.ActiveWindowTitleSampleText).Value.ToString();

                int activeWindowTitleMatchType = Convert.ToInt32(_config.Settings.User.GetByKey("ActiveWindowTitleMatchType", _config.Settings.DefaultSettings.ActiveWindowTitleMatchType).Value);

                switch (activeWindowTitleMatchType)
                {
                case 1:
                    _formSetup.radioButtonCaseSensitiveMatch.Checked = true;
                    break;

                case 2:
                    _formSetup.radioButtonCaseInsensitiveMatch.Checked = true;
                    break;

                case 3:
                    _formSetup.radioButtonRegularExpressionMatch.Checked = true;
                    break;
                }

                // Labels
                _formSetup.checkBoxScreenshotLabel.Checked = Convert.ToBoolean(_config.Settings.User.GetByKey("ApplyScreenshotLabel", _config.Settings.DefaultSettings.ApplyScreenshotLabel).Value);
                PopulateLabelList();

                // Application Focus
                _formSetup.RefreshApplicationFocusList();

                EnableStartCapture();

                CaptureLimitCheck();

                // Set the filter type to be the last selected index that was saved (and if no setting is found just set it to selected index 0).
                // IMPORTANT: Do not attempt to set the same index for Filter Value here as that control is populated based on the selected index of Filter Type.
                comboBoxFilterType.SelectedIndex = Convert.ToInt32(_config.Settings.User.GetByKey("FilterType", 0).Value);

                monthCalendar.SelectionStart = Convert.ToDateTime(_config.Settings.User.GetByKey("SelectedCalendarDay", DateTime.Now).Value);

                // SFTP
                _formFileTransferSettings.checkBoxDeleteLocalFileAfterSuccessfulUpload.Checked = Convert.ToBoolean(_config.Settings.User.GetByKey("SFTPDeleteLocalFileAfterSuccessfulUpload", _config.Settings.DefaultSettings.SFTPDeleteLocalFileAfterSuccessfulUpload).Value);
                _formFileTransferSettings.checkBoxKeepFailedUploads.Checked = Convert.ToBoolean(_config.Settings.User.GetByKey("SFTPKeepFailedUploads", _config.Settings.DefaultSettings.SFTPKeepFailedUploads).Value);

                _log.WriteDebugMessage("Settings loaded");
            }
            catch (Exception ex)
            {
                _screenCapture.ApplicationError = true;
                _log.WriteExceptionMessage("FormMain-Settings::LoadSettings", ex);
            }
        }
Ejemplo n.º 14
0
        private static void CheckAndCreateFiles()
        {
            if (string.IsNullOrEmpty(FileSystem.CommandFile))
            {
                FileSystem.CommandFile = FileSystem.DefaultCommandFile;

                FileSystem.AppendToFile(FileSystem.ConfigFile, "\nCommandFile=" + FileSystem.DefaultCommandFile);

                if (!FileSystem.FileExists(FileSystem.DefaultCommandFile))
                {
                    FileSystem.CreateFile(FileSystem.DefaultCommandFile);
                }
            }

            if (string.IsNullOrEmpty(FileSystem.ApplicationSettingsFile))
            {
                FileSystem.ApplicationSettingsFile = FileSystem.DefaultApplicationSettingsFile;

                FileSystem.AppendToFile(FileSystem.ConfigFile, "\nApplicationSettingsFile=" + FileSystem.DefaultApplicationSettingsFile);

                if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder))
                {
                    FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder);
                }
            }

            if (string.IsNullOrEmpty(FileSystem.UserSettingsFile))
            {
                FileSystem.UserSettingsFile = FileSystem.DefaultUserSettingsFile;

                FileSystem.AppendToFile(FileSystem.ConfigFile, "\nUserSettingsFile=" + FileSystem.DefaultUserSettingsFile);

                if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder))
                {
                    FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder);
                }
            }

            Settings.Initialize();

            Log.WriteMessage("Loading user settings");
            Settings.User.Load();
            Log.WriteDebugMessage("User settings loaded");

            Log.WriteDebugMessage("Attempting upgrade of application settings from old version of application (if needed)");
            Settings.Application.Upgrade();

            Log.WriteDebugMessage("Attempting upgrade of user settings from old version of application (if needed)");
            Settings.User.Upgrade();

            if (string.IsNullOrEmpty(FileSystem.ScreenshotsFile))
            {
                ImageFormatCollection imageFormatCollection = new ImageFormatCollection();
                ScreenCollection      screenCollection      = new ScreenCollection();

                ScreenshotCollection screenshotCollection = new ScreenshotCollection(imageFormatCollection, screenCollection);
                screenshotCollection.SaveToXmlFile(0);
            }

            if (string.IsNullOrEmpty(FileSystem.EditorsFile))
            {
                // Loading the editor collection will automatically create the default editors and add them to the collection.
                EditorCollection editorCollection = new EditorCollection();
                editorCollection.LoadXmlFileAndAddEditors();
            }

            if (string.IsNullOrEmpty(FileSystem.RegionsFile))
            {
                RegionCollection regionCollection = new RegionCollection();
                regionCollection.SaveToXmlFile();
            }

            if (string.IsNullOrEmpty(FileSystem.ScreensFile))
            {
                // Loading the screen collection will automatically create the available screens and add them to the collection.
                ScreenCollection screenCollection = new ScreenCollection();
                screenCollection.LoadXmlFileAndAddScreens(new ImageFormatCollection());
            }

            if (string.IsNullOrEmpty(FileSystem.TriggersFile))
            {
                // Loading triggers will automatically create the default triggers and add them to the collection.
                TriggerCollection triggerCollection = new TriggerCollection();
                triggerCollection.LoadXmlFileAndAddTriggers();
            }

            if (string.IsNullOrEmpty(FileSystem.TagsFile))
            {
                // Loading tags will automatically create the default tags and add them to the collection.
                TagCollection tagCollection = new TagCollection();
                tagCollection.LoadXmlFileAndAddTags();
            }

            if (string.IsNullOrEmpty(FileSystem.SchedulesFile))
            {
                // Loading schedules will automatically create the default schedules and add them to the collection.
                ScheduleCollection scheduleCollection = new ScheduleCollection();
                scheduleCollection.LoadXmlFileAndAddSchedules();
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Loads the user's saved settings.
        /// </summary>
        private void LoadSettings()
        {
            try
            {
                Log.WriteMessage("*** Welcome to " + Settings.ApplicationName + " " + Settings.ApplicationVersion + " (\"" + Settings.ApplicationCodename + "\") ***");
                Log.WriteMessage("Starting application");
                Log.WriteDebugMessage("At this point the application should be able to run normally");
                Log.WriteDebugMessage("but it would be a good idea to check what we found in your autoscreen.conf file");
                Log.WriteDebugMessage("Your autoscreen.conf file is \"" + FileSystem.ConfigFile + "\"");
                Log.WriteDebugMessage("The name and location of it can be changed with the -config command line argument:");
                Log.WriteDebugMessage("autoscreen.exe -config=C:\\MyAutoScreenCapture.conf");
                Log.WriteDebugMessage("Checking what we loaded from your autoscreen.conf file ...");
                Log.WriteDebugMessage("ApplicationSettingsFile=" + FileSystem.ApplicationSettingsFile);
                Log.WriteDebugMessage("UserSettingsFile=" + FileSystem.UserSettingsFile);
                Log.WriteDebugMessage("DebugFolder=" + FileSystem.DebugFolder);
                Log.WriteDebugMessage("LogsFolder=" + FileSystem.LogsFolder);
                Log.WriteDebugMessage("CommandFile=" + FileSystem.CommandFile);
                Log.WriteDebugMessage("ScreenshotsFolder=" + FileSystem.ScreenshotsFolder);
                Log.WriteDebugMessage("ScreenshotsFile=" + FileSystem.ScreenshotsFile);
                Log.WriteDebugMessage("TriggersFile=" + FileSystem.TriggersFile);
                Log.WriteDebugMessage("ScreensFile=" + FileSystem.ScreensFile);
                Log.WriteDebugMessage("RegionsFile=" + FileSystem.RegionsFile);
                Log.WriteDebugMessage("EditorsFile=" + FileSystem.EditorsFile);
                Log.WriteDebugMessage("TagsFile = " + FileSystem.TagsFile);

                Log.WriteDebugMessage("It looks like I successfully parsed your \"" + FileSystem.ConfigFile + "\" file.");
                Log.WriteDebugMessage("I'm now going to attempt to load your personal settings and any screenshots you have taken.");

                Log.WriteMessage("Loading user settings");
                Settings.User.Load();
                Log.WriteDebugMessage("User settings loaded");

                Log.WriteDebugMessage("Attempting upgrade of user settings from old version of application (if needed)");
                Settings.User.Upgrade();

                Log.WriteMessage("Initializing screen capture");
                _screenCapture = new ScreenCapture();

                Log.WriteMessage("Initializing image format collection");
                _imageFormatCollection = new ImageFormatCollection();

                Log.WriteMessage("Initializing editor collection");
                formEditor.EditorCollection.LoadXmlFileAndAddEditors();
                Log.WriteDebugMessage("Number of editors loaded = " + formEditor.EditorCollection.Count);

                Log.WriteMessage("Initializing trigger collection");
                formTrigger.TriggerCollection.LoadXmlFileAndAddTriggers();
                Log.WriteDebugMessage("Number of triggers loaded = " + formTrigger.TriggerCollection.Count);

                Log.WriteMessage("Initializing region collection");
                formRegion.RegionCollection.LoadXmlFileAndAddRegions(_imageFormatCollection);
                Log.WriteDebugMessage("Number of regions loaded = " + formRegion.RegionCollection.Count);

                Log.WriteMessage("Initializing screen collection");
                formScreen.ScreenCollection.LoadXmlFileAndAddScreens(_imageFormatCollection);
                Log.WriteDebugMessage("Number of screens loaded = " + formScreen.ScreenCollection.Count);

                Log.WriteMessage("Initializing tag collection");
                formTag.TagCollection.LoadXmlFileAndAddTags();
                Log.WriteDebugMessage("Number of tags loaded = " + formTag.TagCollection.Count);

                Log.WriteMessage("Initializing schedule collection");
                formSchedule.ScheduleCollection.LoadXmlFileAndAddSchedules();
                Log.WriteDebugMessage("Number of schedules loaded = " + formSchedule.ScheduleCollection.Count);

                Log.WriteMessage("Building screens module");
                BuildScreensModule();

                Log.WriteMessage("Building editors module");
                BuildEditorsModule();

                Log.WriteMessage("Building triggers module");
                BuildTriggersModule();

                Log.WriteMessage("Building regions module");
                BuildRegionsModule();

                Log.WriteMessage("Building tags module");
                BuildTagsModule();

                Log.WriteMessage("Building schedules module");
                BuildSchedulesModule();

                Log.WriteMessage("Building screenshot preview context menu");
                BuildScreenshotPreviewContextualMenu();

                Log.WriteMessage("Building view tab pages");
                BuildViewTabPages();

                Log.WriteMessage("Initializing screenshot collection");
                _screenshotCollection = new ScreenshotCollection(_imageFormatCollection, formScreen.ScreenCollection);

                _screenshotCollection.LoadXmlFile();

                int screenCaptureInterval = Convert.ToInt32(Settings.User.GetByKey("IntScreenCaptureInterval", defaultValue: 60000).Value);
                Log.WriteDebugMessage("IntScreenCaptureInterval = " + screenCaptureInterval);

                if (screenCaptureInterval == 0)
                {
                    screenCaptureInterval = 60000;
                    Log.WriteDebugMessage("WARNING: Screen capture interval was found to be 0 so 60,000 milliseconds (or 1 minute) is being used as the default value");
                }

                Log.WriteDebugMessage("Assigning screen capture interval value to its appropriate hour, minute, second, and millisecond variables");

                decimal screenCaptureIntervalHours = Convert.ToDecimal(TimeSpan.FromMilliseconds(Convert.ToDouble(screenCaptureInterval)).Hours);
                Log.WriteDebugMessage("Hours = " + screenCaptureIntervalHours);

                decimal screenCaptureIntervalMinutes = Convert.ToDecimal(TimeSpan.FromMilliseconds(Convert.ToDouble(screenCaptureInterval)).Minutes);
                Log.WriteDebugMessage("Minutes = " + screenCaptureIntervalMinutes);

                decimal screenCaptureIntervalSeconds = Convert.ToDecimal(TimeSpan.FromMilliseconds(Convert.ToDouble(screenCaptureInterval)).Seconds);
                Log.WriteDebugMessage("Seconds = " + screenCaptureIntervalSeconds);

                decimal screenCaptureIntervalMilliseconds = Convert.ToDecimal(TimeSpan.FromMilliseconds(Convert.ToDouble(screenCaptureInterval)).Milliseconds);
                Log.WriteDebugMessage("Milliseconds = " + screenCaptureIntervalMilliseconds);

                numericUpDownHoursInterval.Value        = screenCaptureIntervalHours;
                numericUpDownMinutesInterval.Value      = screenCaptureIntervalMinutes;
                numericUpDownSecondsInterval.Value      = screenCaptureIntervalSeconds;
                numericUpDownMillisecondsInterval.Value = screenCaptureIntervalMilliseconds;

                numericUpDownCaptureLimit.Value = Convert.ToInt32(Settings.User.GetByKey("IntCaptureLimit", defaultValue: 0).Value);
                Log.WriteDebugMessage("IntCaptureLimit = " + numericUpDownCaptureLimit.Value);

                checkBoxCaptureLimit.Checked = Convert.ToBoolean(Settings.User.GetByKey("BoolCaptureLimit", defaultValue: false).Value);
                Log.WriteDebugMessage("BoolCaptureLimit = " + checkBoxCaptureLimit.Checked);

                checkBoxInitialScreenshot.Checked = Convert.ToBoolean(Settings.User.GetByKey("BoolTakeInitialScreenshot", defaultValue: false).Value);
                Log.WriteDebugMessage("BoolTakeInitialScreenshot = " + checkBoxInitialScreenshot.Checked);

                notifyIcon.Visible = Convert.ToBoolean(Settings.User.GetByKey("BoolShowSystemTrayIcon", defaultValue: true).Value);
                Log.WriteDebugMessage("BoolShowSystemTrayIcon = " + notifyIcon.Visible);

                numericUpDownKeepScreenshotsForDays.Value = Convert.ToDecimal(Settings.User.GetByKey("IntKeepScreenshotsForDays", defaultValue: 30).Value);
                Log.WriteDebugMessage("IntKeepScreenshotsForDays = " + numericUpDownKeepScreenshotsForDays.Value);

                comboBoxScreenshotLabel.Text = Settings.User.GetByKey("StringScreenshotLabel", defaultValue: string.Empty).Value.ToString();
                Log.WriteDebugMessage("StringScreenshotLabel = " + comboBoxScreenshotLabel.Text);

                checkBoxScreenshotLabel.Checked = Convert.ToBoolean(Settings.User.GetByKey("BoolApplyScreenshotLabel", defaultValue: false).Value);

                EnableStartCapture();

                CaptureLimitCheck();

                Log.WriteDebugMessage("Settings loaded");
            }
            catch (Exception ex)
            {
                Log.WriteExceptionMessage("FormMain-Settings::LoadSettings", ex);
            }
        }
Ejemplo n.º 16
0
        private static void CheckAndCreateFiles()
        {
            if (string.IsNullOrEmpty(FileSystem.CommandFile))
            {
                FileSystem.CommandFile = FileSystem.DefaultCommandFile;

                FileSystem.AppendToFile(FileSystem.ConfigFile, "\nCommandFile=" + FileSystem.DefaultCommandFile);

                if (!FileSystem.FileExists(FileSystem.DefaultCommandFile))
                {
                    FileSystem.CreateFile(FileSystem.DefaultCommandFile);
                }
            }

            if (string.IsNullOrEmpty(FileSystem.ApplicationSettingsFile))
            {
                FileSystem.ApplicationSettingsFile = FileSystem.DefaultApplicationSettingsFile;

                FileSystem.AppendToFile(FileSystem.ConfigFile, "\nApplicationSettingsFile=" + FileSystem.DefaultApplicationSettingsFile);

                if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder))
                {
                    FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder);
                }

                SettingCollection applicationSettingsCollection = new SettingCollection
                {
                    Filepath = FileSystem.ApplicationSettingsFile
                };

                applicationSettingsCollection.Save();
            }

            if (string.IsNullOrEmpty(FileSystem.UserSettingsFile))
            {
                FileSystem.UserSettingsFile = FileSystem.DefaultUserSettingsFile;

                FileSystem.AppendToFile(FileSystem.ConfigFile, "\nUserSettingsFile=" + FileSystem.DefaultUserSettingsFile);

                if (!FileSystem.DirectoryExists(FileSystem.DefaultSettingsFolder))
                {
                    FileSystem.CreateDirectory(FileSystem.DefaultSettingsFolder);
                }

                SettingCollection userSettingsCollection = new SettingCollection
                {
                    Filepath = FileSystem.ApplicationSettingsFile
                };

                userSettingsCollection.Save();
            }

            if (string.IsNullOrEmpty(FileSystem.ScreenshotsFile))
            {
                ImageFormatCollection imageFormatCollection = new ImageFormatCollection();
                ScreenCollection      screenCollection      = new ScreenCollection();

                ScreenshotCollection screenshotCollection = new ScreenshotCollection(imageFormatCollection, screenCollection);
                screenshotCollection.SaveToXmlFile(0);
            }

            if (string.IsNullOrEmpty(FileSystem.EditorsFile))
            {
                // Loading the editor collection will automatically create the default editors and add them to the collection.
                EditorCollection editorCollection = new EditorCollection();
                editorCollection.LoadXmlFileAndAddEditors();
            }

            if (string.IsNullOrEmpty(FileSystem.RegionsFile))
            {
                RegionCollection regionCollection = new RegionCollection();
                regionCollection.SaveToXmlFile();
            }

            if (string.IsNullOrEmpty(FileSystem.ScreensFile))
            {
                // Loading the screen collection will automatically create the available screens and add them to the collection.
                ScreenCollection screenCollection = new ScreenCollection();
                screenCollection.LoadXmlFileAndAddScreens(new ImageFormatCollection());
            }

            if (string.IsNullOrEmpty(FileSystem.TriggersFile))
            {
                // Loading triggers will automatically create the default triggers and add them to the collection.
                TriggerCollection triggerCollection = new TriggerCollection();
                triggerCollection.LoadXmlFileAndAddTriggers();
            }

            if (string.IsNullOrEmpty(FileSystem.TagsFile))
            {
                // Loading tags will automatically create the default tags and add them to the collection.
                TagCollection tagCollection = new TagCollection();
                tagCollection.LoadXmlFileAndAddTags();
            }

            if (string.IsNullOrEmpty(FileSystem.SchedulesFile))
            {
                // Loading schedules will automatically create the default schedules and add them to the collection.
                ScheduleCollection scheduleCollection = new ScheduleCollection();
                scheduleCollection.LoadXmlFileAndAddSchedules();
            }
        }
Ejemplo n.º 17
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);
            }
        }
Ejemplo n.º 18
0
        private int SaveToFile(Security security, int jpegQuality, Screenshot screenshot, ScreenshotCollection screenshotCollection)
        {
            int    returnFlag = 0;
            string dirName    = _fileSystem.GetDirectoryName(screenshot.FilePath);

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

                return(returnFlag | (int)ScreenSavingErrorLevels.DirNotFound);
            }

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

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

                // Attempt to process the screenshot before it's saved to disk.
                // This means we'll check for image diff tolerance (if Optimize Screen Capture is enabled).
                if (screenshotCollection.Process(screenshot))
                {
                    // Save the screenshot to disk if it processed successfully.
                    SaveToFile(screenshot, security, jpegQuality);

                    return(returnFlag & (int)ScreenSavingErrorLevels.None);
                }
                else
                {
                    _log.WriteDebugMessage("Could not save screenshot with ID \"" + screenshot.Id + "\" and path \"" + screenshot.FilePath + "\" because the image difference percentage with the previous screenshot's image (" + screenshot.DiffPercentageWithPreviousImage + "%) wasn't significant enough");

                    return(returnFlag | (int)ScreenSavingErrorLevels.ImageDiffNotSignificant);
                }
            }
            catch
            {
                // 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.FilePath}\" because the user may not have the appropriate permissions to access the path");

                return(returnFlag | (int)ScreenSavingErrorLevels.UserNotEnoughPermissions);
            }
        }