public static string SaveNamedTmpFile(Image image, ICaptureDetails captureDetails, OutputFormat outputFormat, int quality, bool reduceColors)
        {
            string pattern = conf.OutputFileFilenamePattern;

            if (pattern == null || string.IsNullOrEmpty(pattern.Trim()))
            {
                pattern = "greenshot ${capturetime}";
            }
            string filename = FilenameHelper.GetFilenameFromPattern(pattern, outputFormat, captureDetails);

            // Prevent problems with "other characters", which causes a problem in e.g. Outlook 2007 or break our HTML
            filename = Regex.Replace(filename, @"[^\d\w\.]", "_");
            // Remove multiple "_"
            filename = Regex.Replace(filename, @"_+", "_");
            string tmpFile = Path.Combine(Path.GetTempPath(), filename);

            LOG.Debug("Creating TMP File: " + tmpFile);

            // Catching any exception to prevent that the user can't write in the directory.
            // This is done for e.g. bugs #2974608, #2963943, #2816163, #2795317, #2789218
            try {
                ImageOutput.Save(image, tmpFile, true, quality, reduceColors, false);
                tmpFileCache.Add(tmpFile, tmpFile);
            } catch (Exception e) {
                // Show the problem
                MessageBox.Show(e.Message, "Error");
                // when save failed we present a SaveWithDialog
                tmpFile = ImageOutput.SaveWithDialog(image, captureDetails);
            }
            return(tmpFile);
        }
Esempio n. 2
0
        //private static string eagerlyCreatedDir = null;
        public static string SaveWithDialog(Image img)
        {
            string         ret  = null;
            AppConfig      conf = AppConfig.GetInstance();
            SaveFileDialog sfd  = CreateSaveFileDialog();
            DialogResult   dr   = sfd.ShowDialog();

            if (dr.Equals(DialogResult.OK))
            {
                try
                {
                    string fn = GetFileNameWithExtension(sfd);
                    ImageOutput.Save(img, fn);
                    ret = fn;
                    conf.Output_FileAs_Fullpath = fn;
                    conf.Store();
                }
                catch (System.Runtime.InteropServices.ExternalException)
                {
                    MessageBox.Show(Language.GetInstance().GetString("error_nowriteaccess").Replace("%path%", sfd.FileName).Replace(@"\\", @"\"), Language.GetInstance().GetString("error"));
                    //eagerlyCreatedDir = null;
                }
            }
            // clean up dir we have created when creating SaveFileDialog (if any)

            /*if(eagerlyCreatedDir != null) {
             *      DirectoryInfo di = new DirectoryInfo(eagerlyCreatedDir);
             *      if(di.Exists && di.GetFiles().Length == 0) {
             *              di.Delete();
             *      }
             *      eagerlyCreatedDir = null;
             * }*/
            return(ret);
        }
Esempio n. 3
0
        /// <summary>
        /// Helper Method for creating an Email with Image Attachment
        /// </summary>
        /// <param name="image">The image to send</param>
        /// <param name="captureDetails">ICaptureDetails</param>
        public static void SendImage(ISurface surface, ICaptureDetails captureDetails)
        {
            string tmpFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings());

            if (tmpFile != null)
            {
                // Store the list of currently active windows, so we can make sure we show the email window later!
                List <WindowDetails> windowsBefore = WindowDetails.GetVisibleWindows();
                // Fallback to MAPI
                // Send the email
                SendImage(tmpFile, captureDetails);
                WindowDetails.ActiveNewerWindows(windowsBefore);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Helper Method for creating an Email with Image Attachment
        /// </summary>
        /// <param name="image">The image to send</param>
        /// <param name="captureDetails">ICaptureDetails</param>
        public static void SendImage(Image image, ICaptureDetails captureDetails)
        {
            string pattern = conf.OutputFileFilenamePattern;

            if (pattern == null || string.IsNullOrEmpty(pattern.Trim()))
            {
                pattern = "greenshot ${capturetime}";
            }
            string filename = FilenameHelper.GetFilenameFromPattern(pattern, conf.OutputFileFormat, captureDetails);

            // Prevent problems with "other characters", which causes a problem in e.g. Outlook 2007 or break our HTML
            filename = Regex.Replace(filename, @"[^\d\w\.]", "_");
            // Remove multiple "_"
            filename = Regex.Replace(filename, @"_+", "_");
            string tmpFile = Path.Combine(Path.GetTempPath(), filename);

            LOG.Debug("Creating TMP File for Email: " + tmpFile);

            // Catching any exception to prevent that the user can't write in the directory.
            // This is done for e.g. bugs #2974608, #2963943, #2816163, #2795317, #2789218
            try {
                ImageOutput.Save(image, tmpFile, true, conf.OutputFileJpegQuality, false);
            } catch (Exception e) {
                // Show the problem
                MessageBox.Show(e.Message, "Error");
                // when save failed we present a SaveWithDialog
                tmpFile = ImageOutput.SaveWithDialog(image, captureDetails);
            }

            if (tmpFile != null)
            {
                // Store the list of currently active windows, so we can make sure we show the email window later!
                List <WindowDetails> windowsBefore = WindowDetails.GetVisibleWindows();
                bool isEmailSend = false;
                if (EmailConfigHelper.HasOutlook() && (conf.OutputEMailFormat == EmailFormat.OUTLOOK_HTML || conf.OutputEMailFormat == EmailFormat.OUTLOOK_TXT))
                {
                    isEmailSend = OutlookExporter.ExportToOutlook(tmpFile, captureDetails);
                }
                if (!isEmailSend && EmailConfigHelper.HasMAPI())
                {
                    // Fallback to MAPI
                    // Send the email and Cleanup the tmp files on exit
                    SendImage(tmpFile, captureDetails.Title, true);
                }
                WindowDetails.ActiveNewerWindows(windowsBefore);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Helper method to create a temp image file
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static string SaveToTmpFile(Image image)
        {
            string tmpFile = Path.GetRandomFileName() + "." + conf.OutputFileFormat.ToString();

            // Prevent problems with "other characters", which could cause problems
            tmpFile = Regex.Replace(tmpFile, @"[^\d\w\.]", "");
            string tmpPath = Path.Combine(Path.GetTempPath(), tmpFile);

            LOG.Debug("Creating TMP File : " + tmpPath);

            try {
                ImageOutput.Save(image, tmpPath, true, conf.OutputFileJpegQuality, false);
            } catch (Exception) {
                return(null);
            }
            return(tmpPath);
        }
Esempio n. 6
0
        /// <summary>
        ///     Helper Method for creating an Email with Image Attachment
        /// </summary>
        /// <param name="surface">The image to send</param>
        /// <param name="captureDetails">ICaptureDetails</param>
        public static void SendImage(ISurface surface, ICaptureDetails captureDetails)
        {
            var tmpFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings());

            if (tmpFile != null)
            {
                // Store the list of currently active windows, so we can make sure we show the email window later!
                //bool isEmailSend = false;
                //if (EmailConfigHelper.HasOutlook() && (CoreConfig.OutputEMailFormat == EmailFormats.Html || CoreConfig.OutputEMailFormat == EmailFormats.Text)) {
                //	isEmailSend = OutlookExporter.ExportToOutlook(tmpFile, captureDetails);
                //}
                if (/*!isEmailSend &&*/ EmailConfigHelper.HasMapi())
                {
                    // Fallback to MAPI
                    // Send the email
                    SendImage(tmpFile, captureDetails.Title);
                }
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Helper Method for creating an Email with Image Attachment
        /// </summary>
        /// <param name="surface">The image to send</param>
        /// <param name="captureDetails">ICaptureDetails</param>
        public static void SendImage(ISurface surface, ICaptureDetails captureDetails)
        {
            string tmpFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings());

            if (tmpFile != null)
            {
                // Store the list of currently active windows, so we can make sure we show the email window later!
                var windowsBefore = WindowDetails.GetVisibleWindows();
                //bool isEmailSend = false;
                //if (EmailConfigHelper.HasOutlook() && (CoreConfig.OutputEMailFormat == EmailFormat.OUTLOOK_HTML || CoreConfig.OutputEMailFormat == EmailFormat.OUTLOOK_TXT)) {
                //	isEmailSend = OutlookExporter.ExportToOutlook(tmpFile, captureDetails);
                //}
                if (/*!isEmailSend &&*/ EmailConfigHelper.HasMapi())
                {
                    // Fallback to MAPI
                    // Send the email
                    SendImage(tmpFile, captureDetails.Title);
                }
                WindowDetails.ActiveNewerWindows(windowsBefore);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Helper Method for creating an Email with Image Attachment
        /// </summary>
        /// <param name="image">The image to send</param>
        /// <param name="captureDetails">ICaptureDetails</param>
        public static void SendImage(Image image, ICaptureDetails captureDetails)
        {
            string tmpFile = ImageOutput.SaveNamedTmpFile(image, captureDetails, conf.OutputFileFormat, conf.OutputFileJpegQuality, conf.OutputFileReduceColors);

            if (tmpFile != null)
            {
                // Store the list of currently active windows, so we can make sure we show the email window later!
                List <WindowDetails> windowsBefore = WindowDetails.GetVisibleWindows();
                bool isEmailSend = false;
                //if (EmailConfigHelper.HasOutlook() && (conf.OutputEMailFormat == EmailFormat.OUTLOOK_HTML || conf.OutputEMailFormat == EmailFormat.OUTLOOK_TXT)) {
                //	isEmailSend = OutlookExporter.ExportToOutlook(tmpFile, captureDetails);
                //}
                if (!isEmailSend && EmailConfigHelper.HasMAPI())
                {
                    // Fallback to MAPI
                    // Send the email
                    SendImage(tmpFile, captureDetails.Title);
                }
                WindowDetails.ActiveNewerWindows(windowsBefore);
            }
        }
        public static string SaveWithDialog(Image image, ICaptureDetails captureDetails)
        {
            string returnValue = null;
            SaveImageFileDialog saveImageFileDialog = new SaveImageFileDialog(captureDetails);
            DialogResult        dialogResult        = saveImageFileDialog.ShowDialog();

            if (dialogResult.Equals(DialogResult.OK))
            {
                try {
                    string fileNameWithExtension = saveImageFileDialog.FileNameWithExtension;
                    // TODO: For now we overwrite, should be changed
                    ImageOutput.Save(image, fileNameWithExtension, true);
                    returnValue = fileNameWithExtension;
                    conf.OutputFileAsFullpath = fileNameWithExtension;
                    IniConfig.Save();
                } catch (System.Runtime.InteropServices.ExternalException) {
                    MessageBox.Show(Language.GetFormattedString(LangKey.error_nowriteaccess, saveImageFileDialog.FileName).Replace(@"\\", @"\"), Language.GetString(LangKey.error));
                }
            }
            return(returnValue);
        }
        //private static string eagerlyCreatedDir = null;

        public static string SaveWithDialog(Image img)
        {
            string         ret  = null;
            AppConfig      conf = AppConfig.GetInstance();
            SaveFileDialog sfd  = CreateSaveFileDialog();

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string fn = GetFileNameWithExtension(sfd);
                    ImageOutput.Save(img, fn);
                    ret = fn;
                    conf.Output_FileAs_Fullpath = fn;
                    conf.Save();
                }
                catch (System.Runtime.InteropServices.ExternalException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            return(ret);
        }
Esempio n. 11
0
 public void SaveToStream(Image img, Stream stream, OutputFormat extension, int quality, bool reduceColors)
 {
     ImageOutput.SaveToStream(img, stream, extension, quality, reduceColors);
 }
Esempio n. 12
0
 public void SaveToStream(Image img, Stream stream, OutputFormat extension, int quality)
 {
     ImageOutput.SaveToStream(img, stream, extension, quality);
 }
Esempio n. 13
0
 public string SaveToTmpFile(Image img, OutputFormat outputFormat, int quality, bool reduceColors)
 {
     return(ImageOutput.SaveToTmpFile(img, outputFormat, quality, reduceColors));
 }
Esempio n. 14
0
        private void DrawImageForPrint(object sender, PrintPageEventArgs e)
        {
            // Create the output settins
            var printOutputSettings = new SurfaceOutputSettings(OutputFormats.png, 100, false);

            ApplyEffects(printOutputSettings);

            var disposeImage = ImageOutput.CreateBitmapFromSurface(_surface, printOutputSettings, out var bitmap);

            try
            {
                var alignment = _coreConfig.OutputPrintCenter ? ContentAlignment.MiddleCenter : ContentAlignment.TopLeft;

                // prepare timestamp
                float  footerStringWidth  = 0;
                float  footerStringHeight = 0;
                string footerString       = null;           //DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
                if (_coreConfig.OutputPrintFooter)
                {
                    footerString = FilenameHelper.FillPattern(_coreConfig.OutputPrintFooterPattern, _captureDetails, false);
                    using (var f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular))
                    {
                        footerStringWidth  = e.Graphics.MeasureString(footerString, f).Width;
                        footerStringHeight = e.Graphics.MeasureString(footerString, f).Height;
                    }
                }

                // Get a rectangle representing the printable Area
                var pageRect = e.PageSettings.PrintableArea;
                if (e.PageSettings.Landscape)
                {
                    var origWidth = pageRect.Width;
                    pageRect.Width  = pageRect.Height;
                    pageRect.Height = origWidth;
                }

                // Subtract the dateString height from the available area, this way the area stays free
                pageRect.Height -= footerStringHeight;

                var gu        = GraphicsUnit.Pixel;
                var imageRect = bitmap.GetBounds(ref gu);
                // rotate the image if it fits the page better
                if (_coreConfig.OutputPrintAllowRotate)
                {
                    if (pageRect.Width > pageRect.Height && imageRect.Width < imageRect.Height || pageRect.Width < pageRect.Height && imageRect.Width > imageRect.Height)
                    {
                        bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        imageRect = bitmap.GetBounds(ref gu);
                        if (alignment.Equals(ContentAlignment.TopLeft))
                        {
                            alignment = ContentAlignment.TopRight;
                        }
                    }
                }
                NativeSizeFloat size      = imageRect.Size;
                var             printRect = new NativeRect(0, 0, size.Round());
                // scale the image to fit the page better
                if (_coreConfig.OutputPrintAllowEnlarge || _coreConfig.OutputPrintAllowShrink)
                {
                    var resizedRect = ScaleHelper.GetScaledSize(imageRect.Size, pageRect.Size, false);
                    if (_coreConfig.OutputPrintAllowShrink && resizedRect.Width < printRect.Width || _coreConfig.OutputPrintAllowEnlarge && resizedRect.Width > printRect.Width)
                    {
                        printRect = printRect.Resize(resizedRect.Round());
                    }
                }

                // align the image
                printRect = ScaleHelper.GetAlignedRectangle(printRect, new NativeRect(0, 0, new NativeSizeFloat(pageRect.Width, pageRect.Height).Round()), alignment).Round();
                if (_coreConfig.OutputPrintFooter)
                {
                    //printRect = new NativeRect(0, 0, printRect.Width, printRect.Height - (dateStringHeight * 2));
                    using (var f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular))
                    {
                        e.Graphics.DrawString(footerString, f, Brushes.Black, pageRect.Width / 2 - footerStringWidth / 2, pageRect.Height);
                    }
                }
                e.Graphics.DrawImage(bitmap, printRect, imageRect, GraphicsUnit.Pixel);
            }
            finally
            {
                if (disposeImage)
                {
                    bitmap?.Dispose();
                }
            }
        }
Esempio n. 15
0
 public string SaveNamedTmpFile(Image image, ICaptureDetails captureDetails, OutputFormat outputFormat, int quality, bool reduceColors)
 {
     return(ImageOutput.SaveNamedTmpFile(image, captureDetails, outputFormat, quality, reduceColors));
 }
Esempio n. 16
0
        public static void SetClipboardData(Image image)
        {
            CleanupTmpFile();
            DataObject ido = new DataObject();

            // This will work for Office and most other applications
            //ido.SetData(DataFormats.Bitmap, true, image);

            MemoryStream bmpStream   = null;
            MemoryStream imageStream = null;
            MemoryStream pngStream   = null;

            try {
                if (config.ClipboardFormats.Contains(ClipboardFormat.PNG))
                {
                    pngStream = new MemoryStream();
                    // PNG works for Powerpoint
                    image.Save(pngStream, ImageFormat.Png);
                    // Set the PNG stream
                    ido.SetData("PNG", false, pngStream);
                }


                if (config.ClipboardFormats.Contains(ClipboardFormat.HTML))
                {
                    bmpStream = new MemoryStream();
                    // Save image as BMP
                    image.Save(bmpStream, ImageFormat.Bmp);

                    imageStream = new MemoryStream();
                    // Copy the source, but skip the "BITMAPFILEHEADER" which has a size of 14
                    imageStream.Write(bmpStream.GetBuffer(), BITMAPFILEHEADER_LENGTH, (int)bmpStream.Length - BITMAPFILEHEADER_LENGTH);

                    // Set the DIB to the clipboard DataObject
                    ido.SetData(DataFormats.Dib, true, imageStream);
                }

                // Set the HTML
                if (config.ClipboardFormats.Contains(ClipboardFormat.HTML))
                {
                    // Mark the clipboard for us as "do not touch"
                    ido.SetData("greenshot", false, "was here!");
                    previousTmpFile = ImageOutput.SaveToTmpFile(image);
                    string html = getClipboardString(image, previousTmpFile);
                    ido.SetText(html, TextDataFormat.Html);
                }
            } finally {
                // we need to use the SetDataOject before the streams are closed otherwise the buffer will be gone!
                // Place the DataObject to the clipboard
                SetDataObject(ido);

                if (pngStream != null)
                {
                    pngStream.Dispose();
                    pngStream = null;
                }

                if (bmpStream != null)
                {
                    bmpStream.Dispose();
                    bmpStream = null;
                }

                if (imageStream != null)
                {
                    imageStream.Dispose();
                    imageStream = null;
                }
            }
        }
        void DrawImageForPrint(object sender, PrintPageEventArgs e)
        {
            // Create the output settins
            SurfaceOutputSettings printOutputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false);

            ApplyEffects(printOutputSettings);

            Image image;
            bool  disposeImage = ImageOutput.CreateImageFromSurface(surface, printOutputSettings, out image);

            try {
                ContentAlignment alignment = conf.OutputPrintCenter ? ContentAlignment.MiddleCenter : ContentAlignment.TopLeft;

                // prepare timestamp
                float  footerStringWidth  = 0;
                float  footerStringHeight = 0;
                string footerString       = null;           //DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
                if (conf.OutputPrintFooter)
                {
                    footerString = FilenameHelper.FillPattern(conf.OutputPrintFooterPattern, captureDetails, false);
                    using (Font f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular)) {
                        footerStringWidth  = e.Graphics.MeasureString(footerString, f).Width;
                        footerStringHeight = e.Graphics.MeasureString(footerString, f).Height;
                    }
                }

                // Get a rectangle representing the printable Area
                RectangleF pageRect = e.PageSettings.PrintableArea;
                if (e.PageSettings.Landscape)
                {
                    float origWidth = pageRect.Width;
                    pageRect.Width  = pageRect.Height;
                    pageRect.Height = origWidth;
                }

                // Subtract the dateString height from the available area, this way the area stays free
                pageRect.Height -= footerStringHeight;

                GraphicsUnit gu        = GraphicsUnit.Pixel;
                RectangleF   imageRect = image.GetBounds(ref gu);
                // rotate the image if it fits the page better
                if (conf.OutputPrintAllowRotate)
                {
                    if ((pageRect.Width > pageRect.Height && imageRect.Width < imageRect.Height) || (pageRect.Width < pageRect.Height && imageRect.Width > imageRect.Height))
                    {
                        image.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        imageRect = image.GetBounds(ref gu);
                        if (alignment.Equals(ContentAlignment.TopLeft))
                        {
                            alignment = ContentAlignment.TopRight;
                        }
                    }
                }

                RectangleF printRect = new RectangleF(0, 0, imageRect.Width, imageRect.Height);
                // scale the image to fit the page better
                if (conf.OutputPrintAllowEnlarge || conf.OutputPrintAllowShrink)
                {
                    SizeF resizedRect = ScaleHelper.GetScaledSize(imageRect.Size, pageRect.Size, false);
                    if ((conf.OutputPrintAllowShrink && resizedRect.Width < printRect.Width) || conf.OutputPrintAllowEnlarge && resizedRect.Width > printRect.Width)
                    {
                        printRect.Size = resizedRect;
                    }
                }

                // align the image
                printRect = ScaleHelper.GetAlignedRectangle(printRect, new RectangleF(0, 0, pageRect.Width, pageRect.Height), alignment);
                if (conf.OutputPrintFooter)
                {
                    //printRect = new RectangleF(0, 0, printRect.Width, printRect.Height - (dateStringHeight * 2));
                    using (Font f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular)) {
                        e.Graphics.DrawString(footerString, f, Brushes.Black, pageRect.Width / 2 - (footerStringWidth / 2), pageRect.Height);
                    }
                }
                e.Graphics.DrawImage(image, printRect, imageRect, GraphicsUnit.Pixel);
            } finally {
                if (disposeImage && image != null)
                {
                    image.Dispose();
                    image = null;
                }
            }
        }
        public static void SetClipboardData(Image image)
        {
            DataObject ido = new DataObject();

            // This will work for Office and most other applications
            //ido.SetData(DataFormats.Bitmap, true, image);

            MemoryStream bmpStream   = null;
            MemoryStream imageStream = null;
            MemoryStream pngStream   = null;

            try {
                // Create PNG stream
                if (config.ClipboardFormats.Contains(ClipboardFormat.PNG) || config.ClipboardFormats.Contains(ClipboardFormat.HTMLDATAURL))
                {
                    pngStream = new MemoryStream();
                    // PNG works for Powerpoint
                    image.Save(pngStream, ImageFormat.Png);
                    pngStream.Seek(0, SeekOrigin.Begin);
                }

                if (config.ClipboardFormats.Contains(ClipboardFormat.PNG))
                {
                    // Set the PNG stream
                    ido.SetData("PNG", false, pngStream);
                }

                if (config.ClipboardFormats.Contains(ClipboardFormat.DIB))
                {
                    bmpStream = new MemoryStream();
                    // Save image as BMP
                    image.Save(bmpStream, ImageFormat.Bmp);
                    imageStream = new MemoryStream();
                    // Copy the source, but skip the "BITMAPFILEHEADER" which has a size of 14
                    imageStream.Write(bmpStream.GetBuffer(), BITMAPFILEHEADER_LENGTH, (int)bmpStream.Length - BITMAPFILEHEADER_LENGTH);

                    // Set the DIB to the clipboard DataObject
                    ido.SetData(DataFormats.Dib, true, imageStream);
                }

                // Set the HTML
                if (config.ClipboardFormats.Contains(ClipboardFormat.HTML))
                {
                    string tmpFile = ImageOutput.SaveToTmpFile(image, OutputFormat.png, config.OutputFileJpegQuality, config.OutputFileReduceColors);
                    string html    = getHTMLString(image, tmpFile);
                    ido.SetText(html, TextDataFormat.Html);
                }
                else if (config.ClipboardFormats.Contains(ClipboardFormat.HTMLDATAURL))
                {
                    string html = getHTMLDataURLString(image, pngStream);
                    ido.SetText(html, TextDataFormat.Html);
                }
            } finally {
                // we need to use the SetDataOject before the streams are closed otherwise the buffer will be gone!
                // Place the DataObject to the clipboard
                SetDataObject(ido);

                if (pngStream != null)
                {
                    pngStream.Dispose();
                    pngStream = null;
                }

                if (bmpStream != null)
                {
                    bmpStream.Dispose();
                    bmpStream = null;
                }

                if (imageStream != null)
                {
                    imageStream.Dispose();
                    imageStream = null;
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Make Capture with specified destinations
        /// </summary>
        private void MakeCapture()
        {
            Thread retrieveWindowDetailsThread = null;

            // This fixes a problem when a balloon is still visible and a capture needs to be taken
            // forcefully removes the balloon!
            if (!CoreConfig.HideTrayicon)
            {
                MainForm.Instance.NotifyIcon.Visible = false;
                MainForm.Instance.NotifyIcon.Visible = true;
            }
            Log.Debug($"Capturing with mode {_captureMode} and using Cursor {_captureMouseCursor}");
            _capture.CaptureDetails.CaptureMode = _captureMode;

            // Get the windows details in a seperate thread, only for those captures that have a Feedback
            // As currently the "elements" aren't used, we don't need them yet
            switch (_captureMode)
            {
            case CaptureMode.Region:
                // Check if a region is pre-supplied!
                if (Rectangle.Empty.Equals(_captureRect))
                {
                    retrieveWindowDetailsThread = PrepareForCaptureWithFeedback();
                }
                break;

            case CaptureMode.Window:
                retrieveWindowDetailsThread = PrepareForCaptureWithFeedback();
                break;
            }

            // Add destinations if no-one passed a handler
            if (_capture.CaptureDetails.CaptureDestinations == null || _capture.CaptureDetails.CaptureDestinations.Count == 0)
            {
                AddConfiguredDestination();
            }

            // Delay for the Context menu
            if (CoreConfig.CaptureDelay > 0)
            {
                Thread.Sleep(CoreConfig.CaptureDelay);
            }
            else
            {
                CoreConfig.CaptureDelay = 0;
            }

            // Capture Mousecursor if we are not loading from file or clipboard, only show when needed
            if (_captureMode != CaptureMode.File && _captureMode != CaptureMode.Clipboard)
            {
                _capture = WindowCapture.CaptureCursor(_capture);
                _capture.CursorVisible = _captureMouseCursor && CoreConfig.CaptureMousepointer;
            }

            switch (_captureMode)
            {
            case CaptureMode.Window:
                _capture = WindowCapture.CaptureScreen(_capture);
                _capture.CaptureDetails.AddMetaData("source", "Screen");
                SetDpi();
                CaptureWithFeedback();
                break;

            case CaptureMode.ActiveWindow:
                if (CaptureActiveWindow())
                {
                    // Capture worked, offset mouse according to screen bounds and capture location
                    _capture.MoveMouseLocation(_capture.ScreenBounds.Location.X - _capture.Location.X, _capture.ScreenBounds.Location.Y - _capture.Location.Y);
                    _capture.CaptureDetails.AddMetaData("source", "Window");
                }
                else
                {
                    _captureMode = CaptureMode.FullScreen;
                    _capture     = WindowCapture.CaptureScreen(_capture);
                    _capture.CaptureDetails.AddMetaData("source", "Screen");
                    _capture.CaptureDetails.Title = "Screen";
                }
                SetDpi();
                HandleCapture();
                break;

            case CaptureMode.IE:
                if (IeCaptureHelper.CaptureIe(_capture, SelectedCaptureWindow) != null)
                {
                    _capture.CaptureDetails.AddMetaData("source", "Internet Explorer");
                    SetDpi();
                    HandleCapture();
                }
                break;

            case CaptureMode.FullScreen:
                // Check how we need to capture the screen
                bool captureTaken = false;
                switch (_screenCaptureMode)
                {
                case ScreenCaptureMode.Auto:
                    Point mouseLocation = User32.GetCursorLocation();
                    foreach (Screen screen in Screen.AllScreens)
                    {
                        if (screen.Bounds.Contains(mouseLocation))
                        {
                            _capture     = WindowCapture.CaptureRectangle(_capture, screen.Bounds);
                            captureTaken = true;
                            break;
                        }
                    }
                    break;

                case ScreenCaptureMode.Fixed:
                    if (CoreConfig.ScreenToCapture > 0 && CoreConfig.ScreenToCapture <= Screen.AllScreens.Length)
                    {
                        _capture     = WindowCapture.CaptureRectangle(_capture, Screen.AllScreens[CoreConfig.ScreenToCapture].Bounds);
                        captureTaken = true;
                    }
                    break;

                case ScreenCaptureMode.FullScreen:
                    // Do nothing, we take the fullscreen capture automatically
                    break;
                }
                if (!captureTaken)
                {
                    _capture = WindowCapture.CaptureScreen(_capture);
                }
                SetDpi();
                HandleCapture();
                break;

            case CaptureMode.Clipboard:
                Image clipboardImage = ClipboardHelper.GetImage();
                if (clipboardImage != null)
                {
                    if (_capture != null)
                    {
                        _capture.Image = clipboardImage;
                    }
                    else
                    {
                        _capture = new Capture(clipboardImage);
                    }
                    _capture.CaptureDetails.Title = "Clipboard";
                    _capture.CaptureDetails.AddMetaData("source", "Clipboard");
                    // Force Editor, keep picker
                    if (_capture.CaptureDetails.HasDestination(PickerDestination.DESIGNATION))
                    {
                        _capture.CaptureDetails.ClearDestinations();
                        _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(EditorDestination.DESIGNATION));
                        _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(PickerDestination.DESIGNATION));
                    }
                    else
                    {
                        _capture.CaptureDetails.ClearDestinations();
                        _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(EditorDestination.DESIGNATION));
                    }
                    HandleCapture();
                }
                else
                {
                    MessageBox.Show(Language.GetString("clipboard_noimage"));
                }
                break;

            case CaptureMode.File:
                Image  fileImage = null;
                string filename  = _capture.CaptureDetails.Filename;

                if (!string.IsNullOrEmpty(filename))
                {
                    try {
                        if (filename.ToLower().EndsWith("." + OutputFormat.greenshot))
                        {
                            ISurface surface = new Surface();
                            surface = ImageOutput.LoadGreenshotSurface(filename, surface);
                            surface.CaptureDetails = _capture.CaptureDetails;
                            DestinationHelper.GetDestination(EditorDestination.DESIGNATION).ExportCapture(true, surface, _capture.CaptureDetails);
                            break;
                        }
                    } catch (Exception e) {
                        Log.Error(e.Message, e);
                        MessageBox.Show(Language.GetFormattedString(LangKey.error_openfile, filename));
                    }
                    try {
                        fileImage = ImageHelper.LoadImage(filename);
                    } catch (Exception e) {
                        Log.Error(e.Message, e);
                        MessageBox.Show(Language.GetFormattedString(LangKey.error_openfile, filename));
                    }
                }
                if (fileImage != null)
                {
                    _capture.CaptureDetails.Title = Path.GetFileNameWithoutExtension(filename);
                    _capture.CaptureDetails.AddMetaData("file", filename);
                    _capture.CaptureDetails.AddMetaData("source", "file");
                    if (_capture != null)
                    {
                        _capture.Image = fileImage;
                    }
                    else
                    {
                        _capture = new Capture(fileImage);
                    }
                    // Force Editor, keep picker, this is currently the only usefull destination
                    if (_capture.CaptureDetails.HasDestination(PickerDestination.DESIGNATION))
                    {
                        _capture.CaptureDetails.ClearDestinations();
                        _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(EditorDestination.DESIGNATION));
                        _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(PickerDestination.DESIGNATION));
                    }
                    else
                    {
                        _capture.CaptureDetails.ClearDestinations();
                        _capture.CaptureDetails.AddDestination(DestinationHelper.GetDestination(EditorDestination.DESIGNATION));
                    }
                    HandleCapture();
                }
                break;

            case CaptureMode.LastRegion:
                if (!CoreConfig.LastCapturedRegion.IsEmpty)
                {
                    _capture = WindowCapture.CaptureRectangle(_capture, CoreConfig.LastCapturedRegion);
                    // TODO: Reactive / check if the elements code is activated
                    //if (windowDetailsThread != null) {
                    //	windowDetailsThread.Join();
                    //}

                    // Set capture title, fixing bug #3569703
                    foreach (WindowDetails window in WindowDetails.GetVisibleWindows())
                    {
                        Point estimatedLocation = new Point(CoreConfig.LastCapturedRegion.X + CoreConfig.LastCapturedRegion.Width / 2, CoreConfig.LastCapturedRegion.Y + CoreConfig.LastCapturedRegion.Height / 2);
                        if (window.Contains(estimatedLocation))
                        {
                            _selectedCaptureWindow        = window;
                            _capture.CaptureDetails.Title = _selectedCaptureWindow.Text;
                            break;
                        }
                    }
                    // Move cursor, fixing bug #3569703
                    _capture.MoveMouseLocation(_capture.ScreenBounds.Location.X - _capture.Location.X, _capture.ScreenBounds.Location.Y - _capture.Location.Y);
                    //capture.MoveElements(capture.ScreenBounds.Location.X - capture.Location.X, capture.ScreenBounds.Location.Y - capture.Location.Y);

                    _capture.CaptureDetails.AddMetaData("source", "screen");
                    SetDpi();
                    HandleCapture();
                }
                break;

            case CaptureMode.Region:
                // Check if a region is pre-supplied!
                if (Rectangle.Empty.Equals(_captureRect))
                {
                    _capture = WindowCapture.CaptureScreen(_capture);
                    _capture.CaptureDetails.AddMetaData("source", "screen");
                    SetDpi();
                    CaptureWithFeedback();
                }
                else
                {
                    _capture = WindowCapture.CaptureRectangle(_capture, _captureRect);
                    _capture.CaptureDetails.AddMetaData("source", "screen");
                    SetDpi();
                    HandleCapture();
                }
                break;

            default:
                Log.Warn("Unknown capture mode: " + _captureMode);
                break;
            }
            // Wait for thread, otherwise we can't dipose the CaptureHelper
            retrieveWindowDetailsThread?.Join();
            if (_capture != null)
            {
                Log.Debug("Disposing capture");
                _capture.Dispose();
            }
        }