示例#1
1
 public void CreateSurfaceFromCaptureEvent(ICapture capture, ISurface surface)
 {
     if (OnSurfaceFromCapture != null) {
         SurfaceFromCaptureEventArgs eventArgs = new SurfaceFromCaptureEventArgs(capture, surface);
         OnSurfaceFromCapture(this, eventArgs);
     }
 }
 /// <summary>
 /// Use the supplied image, and handle it as if it's captured.
 /// </summary>
 /// <param name="imageToImport">Image to handle</param>
 public void ImportCapture(ICapture captureToImport)
 {
     MainForm.instance.BeginInvoke((MethodInvoker)delegate {
         CaptureHelper.ImportCapture(captureToImport);
     });
 }
示例#3
0
        /// <summary>
        /// Here the logic for capturing the IE Content is located
        /// </summary>
        /// <param name="capture">ICapture where the capture needs to be stored</param>
        /// <returns>ICapture with the content (if any)</returns>
        public static ICapture CaptureIE(ICapture capture)
        {
            WindowDetails activeWindow = WindowDetails.GetActiveWindow();

            // Show backgroundform after retrieving the active window..
            BackgroundForm backgroundForm = new BackgroundForm(language.GetString(LangKey.contextmenu_captureie), language.GetString(LangKey.wait_ie_capture));
            backgroundForm.Show();
            //BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(language.GetString(LangKey.contextmenu_captureie), language.GetString(LangKey.wait_ie_capture));
            try {
                //Get IHTMLDocument2 for the current active window
                DocumentContainer documentContainer = GetDocument(activeWindow);

                // Nothing found
                if (documentContainer == null) {
                    LOG.Debug("Nothing to capture found");
                    return null;
                }
                LOG.DebugFormat("Window class {0}", documentContainer.ContentWindow.ClassName);
                LOG.DebugFormat("Window location {0}", documentContainer.ContentWindow.Location);

                // The URL is available unter "document2.url" and can be used to enhance the meta-data etc.
                capture.CaptureDetails.AddMetaData("url", documentContainer.Url);

                // bitmap to return
                Bitmap returnBitmap = null;
                try {
                    returnBitmap = capturePage(documentContainer, capture);
                } catch (Exception e) {
                    LOG.Error("Exception found, ignoring and returning nothing! Error was: ", e);
                }

                if (returnBitmap == null) {
                    return null;
                }

                // Store the bitmap for further processing
                capture.Image = returnBitmap;
                // Store the location of the window
                capture.Location = documentContainer.ContentWindow.Location;
                // Store the title of the Page
                if (documentContainer.Name != null) {
                    capture.CaptureDetails.Title = documentContainer.Name;
                } else {
                    capture.CaptureDetails.Title = activeWindow.Text;
                }

                // Only move the mouse to correct for the capture offset
                capture.MoveMouseLocation(-documentContainer.ViewportRectangle.X, -documentContainer.ViewportRectangle.Y);
                // Used to be: capture.MoveMouseLocation(-(capture.Location.X + documentContainer.CaptureOffset.X), -(capture.Location.Y + documentContainer.CaptureOffset.Y));
            } finally {
                // Always close the background form
                backgroundForm.CloseDialog();
            }
            return capture;
        }
示例#4
0
		// The bulk of the clean-up code is implemented in Dispose(bool)

		/// <summary>
		/// This Dispose is called from the Dispose and the Destructor.
		/// When disposing==true all non-managed resources should be freed too!
		/// </summary>
		/// <param name="disposing"></param>
		protected virtual void Dispose(bool disposing) {
			if (disposing) {
				// Cleanup
			}
			// Unfortunately we can't dispose the capture, this might still be used somewhere else.
			_windows = null;
			_selectedCaptureWindow = null;
			_capture = null;
			// Empty working set after capturing
			if (conf.MinimizeWorkingSetSize) {
				PsAPI.EmptyWorkingSet();
			}
		}
示例#5
0
        // The bulk of the clean-up code is implemented in Dispose(bool)

        /// <summary>
        /// This Dispose is called from the Dispose and the Destructor.
        /// When disposing==true all non-managed resources should be freed too!
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Cleanup
            }
            // Unfortunately we can't dispose the capture, this might still be used somewhere else.
            _windows = null;
            _selectedCaptureWindow = null;
            _capture = null;
            // Empty working set after capturing
            if (CoreConfig.MinimizeWorkingSetSize)
            {
                PsAPI.EmptyWorkingSet();
            }
        }
示例#6
0
        public static bool Grow <T>(this ICapture <T> segment)
        {
            // we can only grow child segments
            if (!segment.CanGrow())
            {
                return(false);
            }

            if (segment.IsReadOnly)
            {
                return(false);
            }

            segment.Count++;
            return(true);
        }
示例#7
0
            /// <summary>
            /// Run the example code.
            /// </summary>
            public static void Main()
            {
                const string MerchantId   = "0";
                const string SharedSecret = "sharedSecret";
                string       orderId      = "12345";
                string       captureId    = "34567";

                IConnector connector = ConnectorFactory.Create(MerchantId, SharedSecret, Client.EuTestBaseUrl);

                Client   client  = new Client(connector);
                IOrder   order   = client.NewOrder(orderId);
                ICapture capture = client.NewCapture(order.Location, captureId);

                ShippingInfo shippingInfo = new ShippingInfo
                {
                    ShippingCompany       = "DHL",
                    ShippingMethod        = "Home",
                    TrackingUri           = new Uri("http://www.dhl.com/content/g0/en/express/tracking.shtml?brand=DHL&AWB=1234567890"),
                    TrackingNumber        = "1234567890",
                    ReturnTrackingNumber  = "E-55-KL",
                    ReturnShippingCompany = "DHL",
                    ReturnTrackingUri     = new Uri("http://www.dhl.com/content/g0/en/express/tracking.shtml?brand=DHL&AWB=98389222")
                };

                AddShippingInfo addShippingInfo = new AddShippingInfo();

                addShippingInfo.ShippingInfo = new List <ShippingInfo>()
                {
                    shippingInfo
                };

                try
                {
                    capture.AddShippingInfo(addShippingInfo);
                }
                catch (ApiException ex)
                {
                    Console.WriteLine(ex.ErrorMessage.ErrorCode);
                    Console.WriteLine(ex.ErrorMessage.ErrorMessages);
                    Console.WriteLine(ex.ErrorMessage.CorrelationId);
                }
                catch (WebException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
示例#8
0
        /// <summary>
        ///     Determine if the king can move out of check by capturing a piece or simply moving.
        /// </summary>
        private bool CanKingMoveOrCaptureOutOfCheck(IKing king, IBoardState gameBoardState)
        {
            var canKingMoveOutOfCheck    = false;
            var canKingCaptureOutOfCheck = false;

            // 1.) Can the king move or capture out of check?

            foreach (ChessPosition position in king.ThreatenSet)
            {
                IMove    move    = ModelLocator.CreateMove(king.Location, position);
                ICapture capture = ModelLocator.CreateCapture(king.Location, position);

                canKingMoveOutOfCheck    |= IsMoveLegal(king, move, gameBoardState);
                canKingCaptureOutOfCheck |= IsCaptureLegal(king, capture, gameBoardState);
            }

            return(canKingMoveOutOfCheck || canKingCaptureOutOfCheck);
        }
示例#9
0
        public CaptureForm(ICapture capture, List <WindowDetails> windows)
        {
            if (currentForm != null)
            {
                LOG.Debug("Found currentForm, Closing already opened CaptureForm");
                currentForm.Close();
                currentForm = null;
                Application.DoEvents();
            }
            currentForm = this;

            // clean up
            this.FormClosed += delegate {
                currentForm = null;
                LOG.Debug("Remove CaptureForm from currentForm");
            };

            this.capture = capture;
            this.windows = windows;
            captureMode  = capture.CaptureDetails.CaptureMode;

            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
            this.Text = "Greenshot capture form";

            // Make sure we never capture the captureform
            WindowDetails.RegisterIgnoreHandle(this.Handle);
            // TODO: Need to call unregister at close

            // set cursor location
            cursorPos = WindowCapture.GetCursorLocation();
            // Offset to screen coordinates
            cursorPos.Offset(-capture.ScreenBounds.X, -capture.ScreenBounds.Y);

            this.SuspendLayout();
            pictureBox.Image = capture.Image;
            this.Bounds      = capture.ScreenBounds;
            this.ResumeLayout();

            // Fix missing focus
            WindowDetails.ToForeground(this.Handle);
        }
示例#10
0
文件: Form1.cs 项目: haivido/Vido
        public Form1()
        {
            InitializeComponent();
              // JPEG http://pasteldth.dyndns.org/cgi-bin/net_jpeg.cgi?ch=2
              // MJPEG http://64.122.208.241:8000/axis-cgi/mjpg/video.cgi?resolution=320x240
              var captureFactory = new CaptureFactory();
              captureFactory.CaptureType = Enums.StreamType.Jpeg;

              capture = captureFactory.Create();
              capture.NewFrame += capture_NewFrame;

              var config = new CaptureConfigs();
              config.Source = @"http://pasteldth.dyndns.org/cgi-bin/net_jpeg.cgi?ch=2";
              config.Username = "******";
              config.Password = "******";
              config.FrameInterval = 0;

              capture.Configs = config;
        }
        public CaptureForm(ICapture capture, List<WindowDetails> windows)
        {
            if (currentForm != null) {
                LOG.Debug("Found currentForm, Closing already opened CaptureForm");
                currentForm.Close();
                currentForm = null;
                Application.DoEvents();
            }
            currentForm = this;

            // clean up
            this.FormClosed += delegate {
                currentForm = null;
                LOG.Debug("Remove CaptureForm from currentForm");
            };

            this.capture = capture;
            this.windows = windows;
            captureMode = capture.CaptureDetails.CaptureMode;

            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
            this.Text = "Greenshot capture form";

            // Make sure we never capture the captureform
            WindowDetails.RegisterIgnoreHandle(this.Handle);
            // TODO: Need to call unregister at close

            // set cursor location
            cursorPos = WindowCapture.GetCursorLocation();
            // Offset to screen coordinates
            cursorPos.Offset(-capture.ScreenBounds.X, -capture.ScreenBounds.Y);

            this.SuspendLayout();
            pictureBox.Image = capture.Image;
            this.Bounds = capture.ScreenBounds;
            this.ResumeLayout();

            // Fix missing focus
            WindowDetails.ToForeground(this.Handle);
        }
示例#12
0
        public ILexeme Create(ILexerRule lexerRule, ICapture <char> segment, int offset)
        {
            if (lexerRule.LexerRuleType != LexerRuleType)
            {
                throw new Exception(
                          $"Unable to create DfaLexeme from type {lexerRule.GetType().FullName}. Expected DfaLexerRule");
            }
            var dfaLexerRule = lexerRule as IDfaLexerRule;

            if (_queue.Count > 0)
            {
                var reusedLexeme = _queue.Dequeue();
                reusedLexeme.Reset(dfaLexerRule, offset);
                return(reusedLexeme);
            }
            var dfaLexeme = new DfaLexeme(dfaLexerRule, segment, offset);

            return(dfaLexeme);
        }
        public ILexeme Create(ILexerRule lexerRule, ICapture <char> segment, int offset)
        {
            if (lexerRule.LexerRuleType != LexerRuleType)
            {
                throw new Exception(
                          $"Unable to create ParseEngineLexeme from type {lexerRule.GetType().FullName}. Expected TerminalLexerRule");
            }

            var grammarLexerRule = lexerRule as IGrammarLexerRule;

            if (_queue.Count == 0)
            {
                return(new ParseEngineLexeme(grammarLexerRule, segment, offset));
            }

            var reusedLexeme = _queue.Dequeue();

            reusedLexeme.Reset(grammarLexerRule, offset);
            return(reusedLexeme);
        }
示例#14
0
        public ILexeme Create(ILexerRule lexerRule, ICapture <char> segment, int offset)
        {
            if (!LexerRuleType.Equals(lexerRule.LexerRuleType))
            {
                throw new Exception(
                          $"Unable to create TerminalLexeme from type {lexerRule.GetType().FullName}. Expected TerminalLexerRule");
            }

            var terminalLexerRule = lexerRule as ITerminalLexerRule;

            if (_queue.Count == 0)
            {
                return(new TerminalLexeme(terminalLexerRule, segment, offset));
            }

            var reusedLexeme = _queue.Dequeue();

            reusedLexeme.Reset(terminalLexerRule, offset);
            return(reusedLexeme);
        }
示例#15
0
        protected override void WriteMatch(ICapture capture)
        {
            if (SpellcheckState?.Data.IgnoredValues.Contains(capture.Value) == true)
            {
                return;
            }

            string result = Replacer.Replace(capture);

            if (result != null)
            {
                _textWriter?.Write(Input.AsSpan(_writerIndex, capture.Index - _writerIndex));
                _textWriter?.Write(result);

                _writerIndex = capture.Index + capture.Length;

                ReplacementCount++;
            }

            SpellcheckState?.ProcessReplacement(Input, capture, result);
        }
示例#16
0
        /// <summary>
        ///     Makes a capture.
        /// </summary>
        /// <param name="capture"></param>
        /// <returns>Returns success of capture.</returns>
        private bool MakeCapture(ICapture capture)
        {
            IPiece capturingPiece = GetPiece(ActivePlayerColor, capture.StartingPosition);

            bool isCaptureLegalEnPassant = IsCaptureLegalEnPassant(capturingPiece, capture, GameBoard);

            if (!IsCaptureLegal(capturingPiece, capture, GameBoard.State) && !isCaptureLegalEnPassant)
            {
                return(false);
            }

            if (isCaptureLegalEnPassant)
            {
                ActivePlayer.Score += ExecuteEnPassantCapture(capture);
            }
            else
            {
                ActivePlayer.Score += ExecuteCapture(capture);
            }

            return(true);
        }
示例#17
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            integerVariable1 = Convert.ToInt32(txtWidthX0.Text);  //"Argument7", "X1");
            integerVariable2 = Convert.ToInt32(txtHeightY0.Text); //("Argument8", "Y1");
            integerVariable3 = Convert.ToInt32(txtWidthX1.Text);  //"Argument9", "X2");
            integerVariable4 = Convert.ToInt32(txtHeightY1.Text); //"Argument10", "Y2");

            video.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.Autofocus, 0);
            //video.SetCaptureProperty(CapProp.Focus, 75);
            ICapture capture = (ICapture)video;
            Mat      img     = capture.QueryFrame();

            _imgRealTime = (Image <Hsv, byte>)null;
            _imgRealTime = new Image <Hsv, byte>(img.Bitmap);
            int       width  = integerVariable3 - integerVariable1;
            int       height = integerVariable4 - integerVariable2;
            Rectangle rect   = new Rectangle(integerVariable1, integerVariable2, width, height);

            _imgRealTime.Draw(rect, new Hsv(0.0, 0.0, (double)byte.MaxValue), 5, Emgu.CV.CvEnum.LineType.AntiAlias, 0);
            CvInvoke.PutText(_imgRealTime, "BarCode: " + _SerialNumberFromBarcode, new Point(100, 60), FontFace.HersheyComplex, 1.0, new Rgb(0, 0, 0).MCvScalar, 2);
            CvInvoke.PutText(_imgRealTime, "OCR: " + _SerialNumberFromOCR, new Point(100, 100), FontFace.HersheyComplex, 1.0, new Rgb(0, 0, 0).MCvScalar, 2);
            pictureBox1.Image = _imgRealTime.Bitmap;
        }
示例#18
0
            /// <summary>
            /// Run the example code.
            /// </summary>
            public static void Main()
            {
                const string MerchantId   = "0";
                const string SharedSecret = "sharedSecret";
                string       orderId      = "12345";
                string       captureId    = "34567";

                IConnector connector = ConnectorFactory.Create(MerchantId, SharedSecret, Client.EuTestBaseUrl);

                Client   client  = new Client(connector);
                IOrder   order   = client.NewOrder(orderId);
                ICapture capture = client.NewCapture(order.Location, captureId);

                UpdateCustomerDetails updateCustomerDetails = new UpdateCustomerDetails()
                {
                    BillingAddress = new Address()
                    {
                        Email = "*****@*****.**",
                        Phone = "57-3895734"
                    }
                };

                try
                {
                    capture.UpdateCustomerDetails(updateCustomerDetails);
                }
                catch (ApiException ex)
                {
                    Console.WriteLine(ex.ErrorMessage.ErrorCode);
                    Console.WriteLine(ex.ErrorMessage.ErrorMessages);
                    Console.WriteLine(ex.ErrorMessage.CorrelationId);
                }
                catch (WebException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
示例#19
0
        /// <summary>
        ///     Does the active player control a piece that can capture the piece threatening the king?
        /// </summary>
        private bool CanThreateningPieceBeCaptured(IPiece threateningPiece)
        {
            foreach (IPiece activePlayerPiece in ActivePlayerPieces)
            {
                activePlayerPiece.GenerateCaptures(GameBoard.State, ActivePlayerBoardState);
                bool canCaptureAt = activePlayerPiece.CanCaptureAt(threateningPiece.Location);

                if (!canCaptureAt)
                {
                    continue;
                }

                ICapture capture = ModelLocator.CreateCapture(activePlayerPiece.Location, threateningPiece.Location);

                bool isCaptureLegal = IsCaptureLegal(activePlayerPiece, capture, GameBoard.State);

                if (isCaptureLegal)
                {
                    return(true);
                }
            }

            return(false);
        }
 public BaseCamera(string CameraIpAddress, string UserName, string Password, string CameraName)
 {
     this.ProcessLock            = new object();
     this.UserName               = UserName;
     this.Password               = Password;
     this.CameraIpAddress        = CameraIpAddress;
     this.IsContinuousRecording  = false;
     this.CurrentFrameQueue      = new Queue(1);
     this.ProcessedFrameQueue    = new Queue(1);
     this.IsFocusWindow          = true;
     this.IsCalculateFrameCentre = true;
     this.IsAutoTrackEnabled     = false;
     if (CameraName != "")
     {
         this.CameraName = CameraName;
     }
     else
     {
         this.CameraName = this.GetType().Name;                 // typeof(this).Name;
     }
     this.Camera          = null;
     this.VideoStreamer   = null;
     this.IsInvertedVideo = false;
 }
示例#21
0
 string TesseractAPI()
 {
     using (var objOcr = OcrApi.Create())
     {
         objOcr.Init(Patagames.Ocr.Enums.Languages.English);
         objOcr.SetVariable("tessedit_char_whitelist", "0123456789-Model:");
         ICapture          capture = (ICapture)video;
         Mat               img     = capture.QueryFrame();
         int               with    = img.Width;
         int               heigh   = img.Height;
         Image <Hsv, byte> image1  = (Image <Hsv, byte>)null;
         image1 = new Image <Hsv, byte>(img.Bitmap);
         int       width  = integerVariable3 - integerVariable1;
         int       height = integerVariable4 - integerVariable2;
         Rectangle rect   = new Rectangle(integerVariable1, integerVariable2, width, height);
         image1.Draw(rect, new Hsv(0.0, 0.0, (double)byte.MaxValue), 10, Emgu.CV.CvEnum.LineType.AntiAlias, 0);
         image1.Save(@"C:\Images\Labe.jpg");
         image1.Dispose();
         var    _bmp = Bitmap.FromFile(@"C:\Images\Labe.jpg");
         string _OCR = objOcr.GetTextFromImage((Bitmap)_bmp);
         _bmp.Dispose();
         return(_OCR);
     }
 }
示例#22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebCamera"/> class.
        /// </summary>
        /// <param name="capture">An implementation of the <see cref="ICapture"/> interface that is going to fetch the web camera frames.</param>
        /// <param name="fps">The desired FPS of the web camera capture.</param>
        /// <param name="width">The width of the web camera capture.</param>
        /// <param name="height">The height of the web camera capture.</param>
        public WebCamera(ICapture capture, int fps = DEFAULT_FPS, int width = DEFAULT_WIDTH, int height = DEFAULT_HEIGHT)
        {
            if (fps < 1)
            {
                throw new ArgumentException($"The FPS has to be greater than 0.");
            }

            if (width < 1 || height < 1)
            {
                throw new ArgumentException($"Invalid resolution. Both width and height have to be greater than 0.");
            }

            this.videoCapture = capture;

            this.Fps    = fps;
            this.Width  = width;
            this.Height = height;
            this.IsOn   = false;

            int interval = 1000 / this.Fps;

            this.timer          = new Timer(interval);
            this.timer.Elapsed += this.QueryFrame;
        }
示例#23
0
        private PdlQualifiedIdentifier VisitQualifiedIdentifierNode(IInternalTreeNode node)
        {
            PdlQualifiedIdentifier repetitionIdentifier = null;
            ICapture <char>        identifier           = null;

            for (int c = 0; c < node.Children.Count; c++)
            {
                var child = node.Children[c];
                switch (child.NodeType)
                {
                case TreeNodeType.Internal:
                    var internalNode = child as IInternalTreeNode;
                    var symbolValue  = internalNode.Symbol.Value;
                    if (PdlGrammar.QualifiedIdentifier == symbolValue)
                    {
                        repetitionIdentifier = VisitQualifiedIdentifierNode(internalNode);
                    }
                    break;

                case TreeNodeType.Token:
                    var tokenNode = child as ITokenTreeNode;
                    var token     = tokenNode.Token;
                    if (token.TokenType.Equals(PdlGrammar.TokenTypes.Identifier))
                    {
                        identifier = token.Capture;
                    }
                    break;
                }
            }
            if (repetitionIdentifier is null)
            {
                return(new PdlQualifiedIdentifier(identifier));
            }

            return(new PdlQualifiedIdentifierConcatenation(identifier, repetitionIdentifier));
        }
示例#24
0
 public void CreateCaptureTakenEvent(ICapture capture)
 {
     if (OnCaptureTaken != null) {
         CaptureTakenEventArgs eventArgs = new CaptureTakenEventArgs(capture);
         OnCaptureTaken(this, eventArgs);
     }
 }
示例#25
0
        /**
           * Finishing the whole Capture with Feedback flow, passing the result on to the HandleCapture
           */
        private void finishCaptureWithFeedback()
        {
            // Get title
             if (selectedCaptureWindow != null)
             {
            if (capture == null)
            {
               capture = new Capture();
            }
            capture.CaptureDetails.Title = selectedCaptureWindow.Text;
             }
             if (capture.CaptureDetails.CaptureMode == CaptureMode.Video)
             {
            if (screenCapture != null)
            {
               screenCapture = null;
            }
            if (captureMode == CaptureMode.Window)
            {
               screenCapture = new ScreenCaptureHelper(selectedCaptureWindow);
            }
            else
            {
               screenCapture = new ScreenCaptureHelper(captureRect);
            }
            screenCapture.RecordMouse = capture.CursorVisible;
            StopCapturing(true);
            screenCapture.Start(10);
             }

             if (captureRect.Height > 0 && captureRect.Width > 0)
             {
            // Take the captureRect, this already is specified as bitmap coordinates
            capture.Crop(captureRect);
            // save for re-capturing later and show recapture context menu option
            RuntimeConfig.LastCapturedRegion = captureRect;

            StopCapturing(false);
            HandleCapture();
             }
        }
示例#26
0
 /// <summary>
 /// This method will use User32 code to capture the specified captureBounds from the screen
 /// </summary>
 /// <param name="capture">ICapture where the captured Bitmap will be stored</param>
 /// <param name="captureBounds">Rectangle with the bounds to capture</param>
 /// <returns>A Capture Object with a part of the Screen as an Image</returns>
 public static ICapture CaptureRectangle(ICapture capture, Rectangle captureBounds)
 {
     if (capture == null)
     {
         capture = new Capture();
     }
     capture.Image = CaptureRectangle(captureBounds);
     capture.Location = captureBounds.Location;
     if (capture.CaptureDetails != null)
     {
         ((Bitmap)capture.Image).SetResolution(capture.CaptureDetails.DpiX, capture.CaptureDetails.DpiY);
     }
     if (capture.Image == null)
     {
         return null;
     }
     return capture;
 }
示例#27
0
 public CaptureHelper(CaptureMode captureMode)
 {
     _captureMode = captureMode;
     _capture = new Capture();
 }
示例#28
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 (!conf.HideTrayicon) {
                MainForm.Instance.NotifyIcon.Visible = false;
                MainForm.Instance.NotifyIcon.Visible = true;
            }
            LOG.Debug(String.Format("Capturing with mode {0} and using Cursor {1}", _captureMode, _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 (conf.CaptureDelay > 0) {
                Thread.Sleep(conf.CaptureDelay);
            } else {
                conf.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);
                if (_captureMouseCursor) {
                    _capture.CursorVisible = conf.CaptureMousepointer;
                } else {
                    _capture.CursorVisible = false;
                }
            }

            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 (conf.ScreenToCapture > 0 && conf.ScreenToCapture <= Screen.AllScreens.Length) {
                                _capture = WindowCapture.CaptureRectangle(_capture, Screen.AllScreens[conf.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 (!conf.LastCapturedRegion.IsEmpty) {
                        _capture = WindowCapture.CaptureRectangle(_capture, conf.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(conf.LastCapturedRegion.X + (conf.LastCapturedRegion.Width / 2), conf.LastCapturedRegion.Y + (conf.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
            if (retrieveWindowDetailsThread != null) {
                retrieveWindowDetailsThread.Join();
            }
            if (_capture != null) {
                LOG.Debug("Disposing capture");
                _capture.Dispose();
            }
        }
示例#29
0
        private void HandleCapture()
        {
            // Flag to see if the image was "exported" so the FileEditor doesn't
            // ask to save the file as long as nothing is done.
            bool outputMade = false;

            // Make sure the user sees that the capture is made
            if (_capture.CaptureDetails.CaptureMode == CaptureMode.File || _capture.CaptureDetails.CaptureMode == CaptureMode.Clipboard) {
                // Maybe not "made" but the original is still there... somehow
                outputMade = true;
            } else {
                // Make sure the resolution is set correctly!
                if (_capture.CaptureDetails != null && _capture.Image != null) {
                    ((Bitmap)_capture.Image).SetResolution(_capture.CaptureDetails.DpiX, _capture.CaptureDetails.DpiY);
                }
                DoCaptureFeedback();
            }

            LOG.Debug("A capture of: " + _capture.CaptureDetails.Title);

            // check if someone has passed a destination
            if (_capture.CaptureDetails.CaptureDestinations == null || _capture.CaptureDetails.CaptureDestinations.Count == 0) {
                AddConfiguredDestination();
            }

            // Create Surface with capture, this way elements can be added automatically (like the mouse cursor)
            Surface surface = new Surface(_capture);
            surface.Modified = !outputMade;

            // Register notify events if this is wanted
            if (conf.ShowTrayNotification && !conf.HideTrayicon) {
                surface.SurfaceMessage += SurfaceMessageReceived;

            }
            // Let the processors do their job
            foreach(IProcessor processor in ProcessorHelper.GetAllProcessors()) {
                if (processor.isActive) {
                    LOG.InfoFormat("Calling processor {0}", processor.Description);
                    processor.ProcessCapture(surface, _capture.CaptureDetails);
                }
            }

            // As the surfaces copies the reference to the image, make sure the image is not being disposed (a trick to save memory)
            _capture.Image = null;

            // Get CaptureDetails as we need it even after the capture is disposed
            ICaptureDetails captureDetails = _capture.CaptureDetails;
            bool canDisposeSurface = true;

            if (captureDetails.HasDestination(PickerDestination.DESIGNATION)) {
                DestinationHelper.ExportCapture(false, PickerDestination.DESIGNATION, surface, captureDetails);
                captureDetails.CaptureDestinations.Clear();
                canDisposeSurface = false;
            }

            // Disable capturing
            _captureMode = CaptureMode.None;
            // Dispose the capture, we don't need it anymore (the surface copied all information and we got the title (if any)).
            _capture.Dispose();
            _capture = null;

            int destinationCount = captureDetails.CaptureDestinations.Count;
            if (destinationCount > 0) {
                // Flag to detect if we need to create a temp file for the email
                // or use the file that was written
                foreach(IDestination destination in captureDetails.CaptureDestinations) {
                    if (PickerDestination.DESIGNATION.Equals(destination.Designation)) {
                        continue;
                    }
                    LOG.InfoFormat("Calling destination {0}", destination.Description);

                    ExportInformation exportInformation = destination.ExportCapture(false, surface, captureDetails);
                    if (EditorDestination.DESIGNATION.Equals(destination.Designation) && exportInformation.ExportMade) {
                        canDisposeSurface = false;
                    }
                }
            }
            if (canDisposeSurface) {
                surface.Dispose();
            }
        }
示例#30
0
        /// <summary>
        /// Surface contructor with a capture
        /// </summary>
        /// <param name="capture"></param>
        public Surface(ICapture capture)
            : this(capture.Image)
        {
            // check if cursor is captured, and visible
            if (capture.Cursor != null && capture.CursorVisible)
            {
                Rectangle cursorRect = new Rectangle(capture.CursorLocation, capture.Cursor.Size);
                Rectangle captureRect = new Rectangle(Point.Empty, capture.Image.Size);
                // check if cursor is on the capture, otherwise we leave it out.
                if (cursorRect.IntersectsWith(captureRect))
                {
                    _cursorContainer = AddIconContainer(capture.Cursor, capture.CursorLocation.X, capture.CursorLocation.Y);
                    SelectElement(_cursorContainer);
                }
            }
            // Make sure the image is NOT disposed, we took the reference directly into ourselves
            ((Capture)capture).NullImage();

            _captureDetails = capture.CaptureDetails;
        }
示例#31
0
        /// <summary>
        /// Capture the supplied Window
        /// </summary>
        /// <param name="windowToCapture">Window to capture</param>
        /// <param name="captureForWindow">The capture to store the details</param>
        /// <param name="windowCaptureMode">What WindowCaptureMode to use</param>
        /// <returns></returns>
        public static ICapture CaptureWindow(WindowDetails windowToCapture, ICapture captureForWindow, WindowCaptureMode windowCaptureMode)
        {
            if (captureForWindow == null) {
                captureForWindow = new Capture();
            }
            Rectangle windowRectangle = windowToCapture.WindowRectangle;

            // When Vista & DWM (Aero) enabled
            bool dwmEnabled = DWM.isDWMEnabled();
            // get process name to be able to exclude certain processes from certain capture modes
            using (Process process = windowToCapture.Process) {
                bool isAutoMode = windowCaptureMode == WindowCaptureMode.Auto;
                // For WindowCaptureMode.Auto we check:
                // 1) Is window IE, use IE Capture
                // 2) Is Windows >= Vista & DWM enabled: use DWM
                // 3) Otherwise use GDI (Screen might be also okay but might lose content)
                if (isAutoMode) {
                    if (conf.IECapture && IECaptureHelper.IsIEWindow(windowToCapture)) {
                        try {
                            ICapture ieCapture = IECaptureHelper.CaptureIE(captureForWindow, windowToCapture);
                            if (ieCapture != null) {
                                return ieCapture;
                            }
                        } catch (Exception ex) {
                            LOG.WarnFormat("Problem capturing IE, skipping to normal capture. Exception message was: {0}", ex.Message);
                        }
                    }

                    // Take default screen
                    windowCaptureMode = WindowCaptureMode.Screen;

                    // Change to GDI, if allowed
                    if (!windowToCapture.isMetroApp && WindowCapture.IsGdiAllowed(process)) {
                        if (!dwmEnabled && isWPF(process)) {
                            // do not use GDI, as DWM is not enabled and the application uses PresentationFramework.dll -> isWPF
                            LOG.InfoFormat("Not using GDI for windows of process {0}, as the process uses WPF", process.ProcessName);
                        } else {
                            windowCaptureMode = WindowCaptureMode.GDI;
                        }
                    }

                    // Change to DWM, if enabled and allowed
                    if (dwmEnabled) {
                        if (windowToCapture.isMetroApp || WindowCapture.IsDwmAllowed(process)) {
                            windowCaptureMode = WindowCaptureMode.Aero;
                        }
                    }
                } else if (windowCaptureMode == WindowCaptureMode.Aero || windowCaptureMode == WindowCaptureMode.AeroTransparent) {
                    if (!dwmEnabled || (!windowToCapture.isMetroApp && !WindowCapture.IsDwmAllowed(process))) {
                        // Take default screen
                        windowCaptureMode = WindowCaptureMode.Screen;
                        // Change to GDI, if allowed
                        if (WindowCapture.IsGdiAllowed(process)) {
                            windowCaptureMode = WindowCaptureMode.GDI;
                        }
                    }
                } else if (windowCaptureMode == WindowCaptureMode.GDI && !WindowCapture.IsGdiAllowed(process)) {
                    // GDI not allowed, take screen
                    windowCaptureMode = WindowCaptureMode.Screen;
                }

                LOG.InfoFormat("Capturing window with mode {0}", windowCaptureMode);
                bool captureTaken = false;
                windowRectangle.Intersect(captureForWindow.ScreenBounds);
                // Try to capture
                while (!captureTaken) {
                    ICapture tmpCapture = null;
                    switch (windowCaptureMode) {
                        case WindowCaptureMode.GDI:
                            if (WindowCapture.IsGdiAllowed(process)) {
                                if (windowToCapture.Iconic) {
                                    // Restore the window making sure it's visible!
                                    windowToCapture.Restore();
                                } else {
                                    windowToCapture.ToForeground();
                                }
                                tmpCapture = windowToCapture.CaptureGDIWindow(captureForWindow);
                                if (tmpCapture != null) {
                                    // check if GDI capture any good, by comparing it with the screen content
                                    int blackCountGDI = ImageHelper.CountColor(tmpCapture.Image, Color.Black, false);
                                    int GDIPixels = tmpCapture.Image.Width * tmpCapture.Image.Height;
                                    int blackPercentageGDI = (blackCountGDI * 100) / GDIPixels;
                                    if (blackPercentageGDI >= 1) {
                                        int screenPixels = windowRectangle.Width * windowRectangle.Height;
                                        using (ICapture screenCapture = new Capture()) {
                                            screenCapture.CaptureDetails = captureForWindow.CaptureDetails;
                                            if (WindowCapture.CaptureRectangleFromDesktopScreen(screenCapture, windowRectangle) != null) {
                                                int blackCountScreen = ImageHelper.CountColor(screenCapture.Image, Color.Black, false);
                                                int blackPercentageScreen = (blackCountScreen * 100) / screenPixels;
                                                if (screenPixels == GDIPixels) {
                                                    // "easy compare", both have the same size
                                                    // If GDI has more black, use the screen capture.
                                                    if (blackPercentageGDI > blackPercentageScreen) {
                                                        LOG.Debug("Using screen capture, as GDI had additional black.");
                                                        // changeing the image will automatically dispose the previous
                                                        tmpCapture.Image = screenCapture.Image;
                                                        // Make sure it's not disposed, else the picture is gone!
                                                        screenCapture.NullImage();
                                                    }
                                                } else if (screenPixels < GDIPixels) {
                                                    // Screen capture is cropped, window is outside of screen
                                                    if (blackPercentageGDI > 50 && blackPercentageGDI > blackPercentageScreen) {
                                                        LOG.Debug("Using screen capture, as GDI had additional black.");
                                                        // changeing the image will automatically dispose the previous
                                                        tmpCapture.Image = screenCapture.Image;
                                                        // Make sure it's not disposed, else the picture is gone!
                                                        screenCapture.NullImage();
                                                    }
                                                } else {
                                                    // Use the GDI capture by doing nothing
                                                    LOG.Debug("This should not happen, how can there be more screen as GDI pixels?");
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (tmpCapture != null) {
                                captureForWindow = tmpCapture;
                                captureTaken = true;
                            } else {
                                // A problem, try Screen
                                windowCaptureMode = WindowCaptureMode.Screen;
                            }
                            break;
                        case WindowCaptureMode.Aero:
                        case WindowCaptureMode.AeroTransparent:
                            if (windowToCapture.isMetroApp || WindowCapture.IsDwmAllowed(process)) {
                                tmpCapture = windowToCapture.CaptureDWMWindow(captureForWindow, windowCaptureMode, isAutoMode);
                            }
                            if (tmpCapture != null) {
                                captureForWindow = tmpCapture;
                                captureTaken = true;
                            } else {
                                // A problem, try GDI
                                windowCaptureMode = WindowCaptureMode.GDI;
                            }
                            break;
                        default:
                            // Screen capture
                            if (windowToCapture.Iconic) {
                                // Restore the window making sure it's visible!
                                windowToCapture.Restore();
                            } else {
                                windowToCapture.ToForeground();
                            }

                            try {
                                captureForWindow = WindowCapture.CaptureRectangleFromDesktopScreen(captureForWindow, windowRectangle);
                                captureTaken = true;
                            } catch (Exception e) {
                                LOG.Error("Problem capturing", e);
                                return null;
                            }
                            break;
                    }
                }
            }

            if (captureForWindow != null) {
                if (windowToCapture != null) {
                    captureForWindow.CaptureDetails.Title = windowToCapture.Text;
                }
            }

            return captureForWindow;
        }
        /// <summary>
        /// Here the logic for capturing the IE Content is located
        /// </summary>
        /// <param name="capture">ICapture where the capture needs to be stored</param>
        /// <returns>ICapture with the content (if any)</returns>
        public static ICapture CaptureIE(ICapture capture)
        {
            WindowDetails activeWindow = WindowDetails.GetActiveWindow();

            // Show backgroundform after retrieving the active window..
            BackgroundForm backgroundForm = new BackgroundForm(Language.GetString(LangKey.contextmenu_captureie), Language.GetString(LangKey.wait_ie_capture));
            backgroundForm.Show();
            //BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(language.GetString(LangKey.contextmenu_captureie), language.GetString(LangKey.wait_ie_capture));
            try {
                //Get IHTMLDocument2 for the current active window
                DocumentContainer documentContainer = GetDocument(activeWindow);

                // Nothing found
                if (documentContainer == null) {
                    LOG.Debug("Nothing to capture found");
                    return null;
                }
                LOG.DebugFormat("Window class {0}", documentContainer.ContentWindow.ClassName);
                LOG.DebugFormat("Window location {0}", documentContainer.ContentWindow.Location);

                // The URL is available unter "document2.url" and can be used to enhance the meta-data etc.
                capture.CaptureDetails.AddMetaData("url", documentContainer.Url);

                // bitmap to return
                Bitmap returnBitmap = null;
                Size pageSize = Size.Empty;
                try {
                    pageSize = PrepareCapture(documentContainer, capture);
                    returnBitmap = capturePage(documentContainer, capture, pageSize);
                } catch (Exception captureException) {
                    LOG.Error("Exception found, ignoring and returning nothing! Error was: ", captureException);
                }
                // Capture the element on the page
                try {
                    if (configuration.IEFieldCapture && capture.CaptureDetails.HasDestination("Editor")) {
                        // clear the current elements, as they are for the window itself
                        capture.Elements.Clear();
                        CaptureElement documentCaptureElement = documentContainer.CreateCaptureElements(pageSize);
                        foreach(DocumentContainer frameDocument in documentContainer.Frames) {
                            CaptureElement frameCaptureElement = frameDocument.CreateCaptureElements(Size.Empty);
                            if (frameCaptureElement != null) {
                                documentCaptureElement.Children.Add(frameCaptureElement);
                            }
                        }
                        capture.AddElement(documentCaptureElement);
                        // Offset the elements, as they are "back offseted" later...
                        Point windowLocation = documentContainer.ContentWindow.WindowRectangle.Location;
                        capture.MoveElements(-(capture.ScreenBounds.Location.X-windowLocation.X), -(capture.ScreenBounds.Location.Y-windowLocation.Y));
                    }
                } catch (Exception elementsException) {
                    LOG.Warn("An error occurred while creating the capture elements: ", elementsException);
                }

                if (returnBitmap == null) {
                    return null;
                }

                // Store the bitmap for further processing
                capture.Image = returnBitmap;
                // Store the location of the window
                capture.Location = documentContainer.ContentWindow.Location;

                // Store the title of the page
                if (documentContainer.Name != null) {
                    capture.CaptureDetails.Title = documentContainer.Name;
                } else {
                    capture.CaptureDetails.Title = activeWindow.Text;
                }

                // Store the URL of the page
                if (documentContainer.Url != null) {
                    Uri uri = new Uri(documentContainer.Url);
                    capture.CaptureDetails.AddMetaData("URL", uri.OriginalString);
                    // As the URL can hardly be used in a filename, the following can be used
                    if (!string.IsNullOrEmpty(uri.Scheme)) {
                        capture.CaptureDetails.AddMetaData("URL_SCHEME", uri.Scheme);
                    }
                    if (!string.IsNullOrEmpty(uri.DnsSafeHost)) {
                        capture.CaptureDetails.AddMetaData("URL_HOSTNAME", uri.DnsSafeHost);
                    }
                    if (!string.IsNullOrEmpty(uri.AbsolutePath)) {
                        capture.CaptureDetails.AddMetaData("URL_PATH", uri.AbsolutePath);
                    }
                    if (!string.IsNullOrEmpty(uri.Query)) {
                        capture.CaptureDetails.AddMetaData("URL_QUERY", uri.Query);
                    }
                    if (!string.IsNullOrEmpty(uri.UserInfo)) {
                        capture.CaptureDetails.AddMetaData("URL_USER", uri.UserInfo);
                    }
                    capture.CaptureDetails.AddMetaData("URL_PORT", uri.Port.ToString());
                }

                // Only move the mouse to correct for the capture offset
                capture.MoveMouseLocation(-documentContainer.ViewportRectangle.X, -documentContainer.ViewportRectangle.Y);
                // Used to be: capture.MoveMouseLocation(-(capture.Location.X + documentContainer.CaptureOffset.X), -(capture.Location.Y + documentContainer.CaptureOffset.Y));
            } finally {
                // Always close the background form
                backgroundForm.CloseDialog();
            }
            return capture;
        }
示例#33
0
        public Surface(ICapture capture)
            : this(capture.Image)
        {
            // Make sure the image is NOT disposed, we took the reference directly into ourselves
            ((Capture)capture).NullImage();

            if (capture.Cursor != null && capture.CursorVisible) {
                cursorContainer = AddIconContainer(capture.Cursor, capture.CursorLocation.X, capture.CursorLocation.Y);
                SelectElement(cursorContainer);
            }
            captureDetails = capture.CaptureDetails;
        }
        /// <summary>
        /// Prepare the calculates for all the frames, move and fit...
        /// </summary>
        /// <param name="documentContainer"></param>
        /// <param name="capture"></param>
        /// <returns>Size of the complete page</returns>
        private static Size PrepareCapture(DocumentContainer documentContainer, ICapture capture)
        {
            // Calculate the page size
            int pageWidth = documentContainer.ScrollWidth;
            int pageHeight = documentContainer.ScrollHeight;

            // Here we loop over all the frames and try to make sure they don't overlap
            bool movedFrame;
            do {
                movedFrame = false;
                foreach(DocumentContainer currentFrame in documentContainer.Frames) {
                    foreach(DocumentContainer otherFrame in documentContainer.Frames) {
                        if (otherFrame.ID == currentFrame.ID) {
                            continue;
                        }
                        // check if we need to move
                        if (otherFrame.DestinationRectangle.IntersectsWith(currentFrame.DestinationRectangle) && !otherFrame.SourceRectangle.IntersectsWith(currentFrame.SourceRectangle)) {
                            bool horizalResize = currentFrame.SourceSize.Width < currentFrame.DestinationSize.Width;
                            bool verticalResize = currentFrame.SourceSize.Width < currentFrame.DestinationSize.Width;
                            bool horizalMove = currentFrame.SourceLeft < currentFrame.DestinationLeft;
                            bool verticalMove = currentFrame.SourceTop < currentFrame.DestinationTop;
                            bool leftOf = currentFrame.SourceRight <= otherFrame.SourceLeft;
                            bool belowOf = currentFrame.SourceBottom <= otherFrame.SourceTop;

                            if ((horizalResize || horizalMove) && leftOf) {
                                // Current frame resized horizontally, so move other horizontally
                                LOG.DebugFormat("Moving Frame {0} horizontally to the right of {1}", otherFrame.Name, currentFrame.Name);
                                otherFrame.DestinationLeft = currentFrame.DestinationRight;
                                movedFrame = true;
                            } else if ((verticalResize || verticalMove) && belowOf){
                                // Current frame resized vertically, so move other vertically
                                LOG.DebugFormat("Moving Frame {0} vertically to the bottom of {1}", otherFrame.Name, currentFrame.Name);
                                otherFrame.DestinationTop = currentFrame.DestinationBottom;
                                movedFrame = true;
                            } else {
                                LOG.DebugFormat("Frame {0} intersects with {1}", otherFrame.Name, currentFrame.Name);
                            }
                        }
                    }
                }
            } while(movedFrame);

            bool movedMouse = false;
            // Correct cursor location to be inside the window
            capture.MoveMouseLocation(-documentContainer.ContentWindow.Location.X, -documentContainer.ContentWindow.Location.Y);
            // See if the page has the correct size, as we capture the full frame content AND might have moved them
            // the normal pagesize will no longer be enough
            foreach(DocumentContainer frameData in documentContainer.Frames) {
                if (!movedMouse && frameData.SourceRectangle.Contains(capture.CursorLocation)) {
                    // Correct mouse cursor location for scrolled position (so it shows on the capture where it really was)
                    capture.MoveMouseLocation(frameData.ScrollLeft, frameData.ScrollTop);
                    movedMouse = true;
                    // Apply any other offset changes
                    int offsetX = frameData.DestinationLocation.X - frameData.SourceLocation.X;
                    int offsetY = frameData.DestinationLocation.Y - frameData.SourceLocation.Y;
                    capture.MoveMouseLocation(offsetX, offsetY);
                }

                //Get Frame Width & Height
                pageWidth = Math.Max(pageWidth, frameData.DestinationRight);
                pageHeight = Math.Max(pageHeight, frameData.DestinationBottom);
            }

            // If the mouse hasn't been moved, it wasn't on a frame. So correct the mouse according to the scroll position of the document
            if (!movedMouse) {
                // Correct mouse cursor location
                capture.MoveMouseLocation(documentContainer.ScrollLeft, documentContainer.ScrollTop);
            }

            // Limit the size as the editor currently can't work with sizes > short.MaxValue
            if (pageWidth > short.MaxValue) {
                LOG.WarnFormat("Capture has a width of {0} which bigger than the maximum supported {1}, cutting width to the maxium.", pageWidth, short.MaxValue);
                pageWidth = Math.Min(pageWidth, short.MaxValue);
            }
            if (pageHeight > short.MaxValue) {
                LOG.WarnFormat("Capture has a height of {0} which bigger than the maximum supported {1}, cutting height to the maxium", pageHeight, short.MaxValue);
                pageHeight = Math.Min(pageHeight, short.MaxValue);
            }
            return new Size(pageWidth, pageHeight);
        }
        /// <summary>
        /// Capture the actual page (document)
        /// </summary>
        /// <param name="documentContainer">The document wrapped in a container</param>
        /// <returns>Bitmap with the page content as an image</returns>
        private static Bitmap capturePage(DocumentContainer documentContainer, ICapture capture, Size pageSize)
        {
            WindowDetails contentWindowDetails = documentContainer.ContentWindow;

            //Create a target bitmap to draw into with the calculated page size
            Bitmap returnBitmap = new Bitmap(pageSize.Width, pageSize.Height, PixelFormat.Format24bppRgb);
            using (Graphics graphicsTarget = Graphics.FromImage(returnBitmap)) {
                // Clear the target with the backgroundcolor
                Color clearColor = documentContainer.BackgroundColor;
                LOG.DebugFormat("Clear color: {0}", clearColor);
                graphicsTarget.Clear(clearColor);

                // Get the base document & draw it
                drawDocument(documentContainer, contentWindowDetails, graphicsTarget);

                // Loop over the frames and clear their source area so we don't see any artefacts
                foreach(DocumentContainer frameDocument in documentContainer.Frames) {
                    using(Brush brush = new SolidBrush(clearColor)) {
                        graphicsTarget.FillRectangle(brush, frameDocument.SourceRectangle);
                    }
                }
                // Loop over the frames and capture their content
                foreach(DocumentContainer frameDocument in documentContainer.Frames) {
                    drawDocument(frameDocument, contentWindowDetails, graphicsTarget);
                }
            }
            return returnBitmap;
        }
示例#36
0
        /// <summary>
        /// Make Capture with specified destinations
        /// </summary>
        /// <param name="mode">CaptureMode</param>
        /// <param name="captureMouseCursor">bool false if the mouse should not be captured, true if the configuration should be checked</param>
        /// <param name="captureDestinations">List<CaptureDestination> with destinations</param>
        private void MakeCapture(CaptureMode mode, bool captureMouseCursor, ICapture newCapture)
        {
            if (screenCapture != null)
             {
            screenCapture.Stop();
            screenCapture = null;
            return;
             }
             if (captureMode != CaptureMode.None)
             {
            LOG.Warn(String.Format("Capture started while capturing, current mode = {0} new capture was {1}.", captureMode, mode));
            return;
             }
             else
             {
            LOG.Debug(String.Format("MakeCapture({0}, {1})", mode, captureMouseCursor));
             }
             captureMode = mode;

             PrepareForCaptureWithFeedback(mode);

             // cleanup the previos information if there is still any
             if (capture != null)
             {
            LOG.Debug("Capture wasn't disposed yet, this would suggest a leak");
            capture.Dispose();
            capture = null;
             }
             // Use the supplied Capture information
             capture = newCapture;
             if (capture == null)
             {
            capture = new Capture();
             }
             capture.CaptureDetails.CaptureMode = mode;

             // Workaround for proble with DPI retrieval, the FromHwnd activates the window...
             WindowDetails previouslyActiveWindow = WindowDetails.GetActiveWindow();
             // Workaround for changed DPI settings in Windows 7
             using (Graphics graphics = Graphics.FromHwnd(this.Handle))
             {
            capture.CaptureDetails.DpiX = graphics.DpiX;
            capture.CaptureDetails.DpiY = graphics.DpiY;
             }
             if (previouslyActiveWindow != null)
             {
            // Set previouslyActiveWindow as foreground window
            previouslyActiveWindow.ToForeground();
             }

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

             // Allways capture Mousecursor, only show when needed
             capture = WindowCapture.CaptureCursor(capture);
             capture.CursorVisible = false;
             // Check if needed
             if (captureMouseCursor && mode != CaptureMode.Clipboard && mode != CaptureMode.File)
             {
            capture.CursorVisible = conf.CaptureMousepointer;
             }

             switch (mode)
             {
            case CaptureMode.Window:
               capture = WindowCapture.CaptureScreen(capture);
               capture.CaptureDetails.AddMetaData("source", "Screen");
               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";
               }
               // Make sure capturing is stopped at any cost
               StopCapturing(false);
               HandleCapture();
               break;
            case CaptureMode.IE:
               if (IECaptureHelper.CaptureIE(capture) != null)
               {
                  capture.CaptureDetails.AddMetaData("source", "Internet Explorer");
                  HandleCapture();
               }
               else
               {
                  StopCapturing(true);
               }
               break;
            case CaptureMode.FullScreen:
               capture = WindowCapture.CaptureScreen(capture);
               HandleCapture();
               break;
            case CaptureMode.Clipboard:
               Image clipboardImage = null;
               string text = "Clipboard";
               if (ClipboardHelper.ContainsImage())
               {
                  clipboardImage = ClipboardHelper.GetImage();
               }
               if (clipboardImage != null)
               {
                  if (capture != null)
                  {
                     capture.Image = clipboardImage;
                  }
                  else
                  {
                     capture = new Capture(clipboardImage);
                  }
                  string title = ClipboardHelper.GetText();
                  if (title == null || title.Trim().Length == 0)
                  {
                     title = "Clipboard";
                  }
                  capture.CaptureDetails.Title = title;
                  capture.CaptureDetails.AddMetaData("source", "Clipboard");
                  // Force Editor
                  capture.CaptureDetails.AddDestination(CaptureDestination.Editor);
                  HandleCapture();
               }
               else
               {
                  MessageBox.Show("Couldn't create bitmap from : " + text);
               }
               break;
            case CaptureMode.File:
               Bitmap fileBitmap = null;
               bool isSaveSupported = true;
               string filename = capture.CaptureDetails.Filename;
               if (!string.IsNullOrEmpty(filename))
               {
                  try
                  {
                     fileBitmap = ImageHelper.LoadBitmap(filename, ref isSaveSupported);
                  }
                  catch (Exception e)
                  {
                     LOG.Error(e.Message, e);
                     MessageBox.Show(lang.GetFormattedString(LangKey.error_openfile, filename));
                  }
               }
               if (fileBitmap != null)
               {
                  capture.CaptureDetails.Title = Path.GetFileNameWithoutExtension(filename);
                  capture.CaptureDetails.AddMetaData("file", filename);
                  capture.CaptureDetails.AddMetaData("source", "file");
                  if (capture != null)
                  {
                     capture.Image = fileBitmap;
                  }
                  else
                  {
                     capture = new Capture(fileBitmap);
                  }
                  // Force Editor, this is currently the only usefull destination
                  capture.CaptureDetails.AddDestination(CaptureDestination.Editor);
                  if (!isSaveSupported)
                  {
                     // We can't save icon & wmf, don't supply the filename
                     HandleCapture();
                  }
                  else
                  {
                     HandleCapture(filename);
                  }
               }
               else
               {
                  // "semi" Fix for Bug #3430555
                  StopCapturing(true);
               }
               break;
            case CaptureMode.LastRegion:
               if (!RuntimeConfig.LastCapturedRegion.Equals(Rectangle.Empty))
               {
                  capture = WindowCapture.CaptureScreen(capture);
                  capture.Crop(RuntimeConfig.LastCapturedRegion);
                  capture.CaptureDetails.AddMetaData("source", "screen");
                  HandleCapture();
               }
               else
               {
                  // Fix for Bug #3430555
                  StopCapturing(true);
               }
               break;
            case CaptureMode.Region:
               capture = WindowCapture.CaptureScreen(capture);
               capture.CaptureDetails.AddMetaData("source", "screen");
               CaptureWithFeedback();
               break;
            case CaptureMode.Video:
               capture = WindowCapture.CaptureScreen(capture);
               // Set the capturemode to be window
               captureMode = CaptureMode.Window;
               capture.CaptureDetails.AddMetaData("source", "Video");
               CaptureWithFeedback();
               break;
            default:
               LOG.Warn("Unknown capture mode: " + mode);
               break;
             }
        }
示例#37
0
        private ICapture AddConfiguredDestination(ICapture capture)
        {
            if (conf.OutputDestinations.Contains(Destination.FileDefault))
             {
            capture.CaptureDetails.AddDestination(CaptureDestination.File);
             }

             if (conf.OutputDestinations.Contains(Destination.FileWithDialog))
             {
            capture.CaptureDetails.AddDestination(CaptureDestination.FileWithDialog);
             }

             if (conf.OutputDestinations.Contains(Destination.Clipboard))
             {
            capture.CaptureDetails.AddDestination(CaptureDestination.Clipboard);
             }

             if (conf.OutputDestinations.Contains(Destination.Printer))
             {
            capture.CaptureDetails.AddDestination(CaptureDestination.Printer);
             }

             if (conf.OutputDestinations.Contains(Destination.Editor))
             {
            capture.CaptureDetails.AddDestination(CaptureDestination.Editor);
             }

             if (conf.OutputDestinations.Contains(Destination.EMail))
             {
            capture.CaptureDetails.AddDestination(CaptureDestination.EMail);
             }

             if (conf.OutputDestinations.Contains(Destination.espUrl))
             {
            capture.CaptureDetails.AddDestination(CaptureDestination.espUrl);
             }

             return capture;
        }
示例#38
0
 public static void ImportCapture(ICapture captureToImport)
 {
     using (CaptureHelper captureHelper = new CaptureHelper(CaptureMode.File)) {
         captureHelper._capture = captureToImport;
         captureHelper.HandleCapture();
     }
 }
示例#39
0
        private void HandleCapture(string fullPath)
        {
            if (capture == null)
             {
            StopCapturing(true);
             }

             // Flag to see if the image was "exported" so the FileEditor doesn't
             // ask to save the file as long as nothing is done.
             bool outputMade = false;

             // Make sure the user sees that the capture is made
             if (capture.CaptureDetails.CaptureMode != CaptureMode.File && capture.CaptureDetails.CaptureMode != CaptureMode.Clipboard)
             {
            DoCaptureFeedback();
             }
             else
             {
            // If File || Clipboard
            // Maybe not "made" but the original is still there... somehow
            outputMade = true;
             }

             LOG.Debug("A capture of: " + capture.CaptureDetails.Title);

             // Create event OnCaptureTaken for all Plugins
             PluginHelper.instance.CreateCaptureTakenEvent(capture);

             // check if someone has passed a handler
             if (capture.CaptureDetails.CaptureHandler != null)
             {
            CaptureTakenEventArgs eventArgs = new CaptureTakenEventArgs(capture);
            capture.CaptureDetails.CaptureHandler(this, eventArgs);
             }
             else if (capture.CaptureDetails.CaptureDestinations == null || capture.CaptureDetails.CaptureDestinations.Count == 0)
             {
            AddConfiguredDestination(capture);
             }

             // Create Surface with capture, this way elements can be added automatically (like the mouse cursor)
             Surface surface = new Surface(capture);

             // As the surfaces copies the reference to the image, make sure the image is not being disposed (a trick to save memory)
             capture.Image = null;

             // Call plugins to do something with the screenshot
             PluginHelper.instance.CreateSurfaceFromCaptureEvent(capture, surface);

             // Disable capturing
             captureMode = CaptureMode.None;

             // Retrieve important information from the Capture object
             ICaptureDetails captureDetails = capture.CaptureDetails;
             List<CaptureDestination> captureDestinations = capture.CaptureDetails.CaptureDestinations;

             // Dispose the capture, we don't need it anymore (the surface copied all information and we got the title (if any)).
             capture.Dispose();
             capture = null;

             // Want to add more stuff to the surface?? DO IT HERE!
             int destinationsCount = captureDestinations.Count;
             if (captureDestinations.Contains(CaptureDestination.Editor))
             {
            destinationsCount--;
             }
             if (destinationsCount > 0)
             {
            // Create Image for writing/printing etc and use "using" as all code paths either output the image or copy the image
            using (Image image = surface.GetImageForExport())
            {
               // Flag to detect if we need to create a temp file for the email
               // or use the file that was written
               bool fileWritten = false;

               if (captureDestinations.Contains(CaptureDestination.espUrl))
               {
                  string title = captureDetails.Title;
                  if (string.IsNullOrEmpty(title))
                  {
                     title = "screen_" + captureDetails.DateTime.ToString("yyyyMMddHHmmssfff");
                  }

                  using (var ms = new MemoryStream())
                  {
                     ImageOutput.SaveToStream(image, ms, OutputFormat.png, 1);
                     ms.Seek(0, SeekOrigin.Begin);
                     new EspUrlClient().Upload(ms, title + ".png");
                  }
               }

               if (captureDestinations.Contains(CaptureDestination.File))
               {
                  string pattern = conf.OutputFileFilenamePattern;
                  if (pattern == null || string.IsNullOrEmpty(pattern.Trim()))
                  {
                     pattern = "espurl ${capturetime}";
                  }
                  string filename = FilenameHelper.GetFilenameFromPattern(pattern, conf.OutputFileFormat, captureDetails);
                  string filepath = FilenameHelper.FillVariables(conf.OutputFilePath, false);
                  fullPath = Path.Combine(filepath, filename);

                  // 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, #3004642
                  try
                  {
                     // TODO: For now we overwrite, but this should be fixed some time
                     ImageOutput.Save(image, fullPath, true);
                     fileWritten = true;
                     outputMade = true;
                  }
                  catch (Exception e)
                  {
                     LOG.Error("Error saving screenshot!", e);
                     // Show the problem
                     MessageBox.Show(lang.GetString(LangKey.error_save), lang.GetString(LangKey.error));
                     // when save failed we present a SaveWithDialog
                     fullPath = ImageOutput.SaveWithDialog(image, captureDetails);
                     fileWritten = (fullPath != null);
                  }
               }

               if (captureDestinations.Contains(CaptureDestination.FileWithDialog))
               {
                  fullPath = ImageOutput.SaveWithDialog(image, captureDetails);
                  fileWritten = (fullPath != null);
                  outputMade = outputMade || fileWritten;
               }

               if (captureDestinations.Contains(CaptureDestination.Clipboard))
               {
                  ClipboardHelper.SetClipboardData(image);
                  outputMade = true;
               }

               if (captureDestinations.Contains(CaptureDestination.Printer))
               {
                  PrinterSettings printerSettings = new PrintHelper(image, captureDetails).PrintWithDialog();
                  outputMade = outputMade || printerSettings != null;
               }

               if (captureDestinations.Contains(CaptureDestination.EMail))
               {
                  if (!fileWritten)
                  {
                     MapiMailMessage.SendImage(image, captureDetails);
                  }
                  else
                  {
                     MapiMailMessage.SendImage(fullPath, captureDetails.Title, false);
                  }
                  // Don't know how to handle a cancel in the email
                  outputMade = true;
               }
            }
             }
             // Make sure we don't have garbage before opening the screenshot
             GC.Collect();
             GC.WaitForPendingFinalizers();

             // If the editor is opened, let it Dispose the surface!
             if (captureDestinations.Contains(CaptureDestination.Editor))
             {
            try
            {
               ImageEditorForm editor = new ImageEditorForm(surface, outputMade);

               if (!string.IsNullOrEmpty(fullPath))
               {
                  editor.SetImagePath(fullPath);
               }
               editor.Show();
               editor.Activate();
               LOG.Debug("Finished opening Editor");
            }
            catch (Exception e)
            {
               // Dispose the surface when an error is caught
               surface.Dispose();
               throw e;
            }
             }
             else
             {
            // Dispose the surface, we are done with it!
            surface.Dispose();
             }

             // Make CaptureForm invisible
             this.Visible = false;
             // Hiding makes the editor (if any) get focus
             this.Hide();
        }
示例#40
0
        void PictureBoxMouseMove(object sender, MouseEventArgs e)
        {
            Point lastPos = new Point(cursorPos.X, cursorPos.Y);
             cursorPos = WindowCapture.GetCursorLocation();
             // Make sure the mouse coordinates are fixed, when pressing shift
             cursorPos = MouseHelper.FixMouseCoordinates(cursorPos);
             // As the cursorPos is not in Bitmap coordinates, we need to correct.
             cursorPos.Offset(-capture.ScreenBounds.Location.X, -capture.ScreenBounds.Location.Y);
             Rectangle lastCaptureRect = new Rectangle(captureRect.Location, captureRect.Size);
             WindowDetails lastWindow = selectedCaptureWindow;
             bool horizontalMove = false;
             bool verticalMove = false;

             if (lastPos.X != cursorPos.X)
             {
            horizontalMove = true;
             }
             if (lastPos.Y != cursorPos.Y)
             {
            verticalMove = true;
             }

             if (captureMode == CaptureMode.Region && mouseDown)
             {
            captureRect = GuiRectangle.GetGuiRectangle(cursorPos.X, cursorPos.Y, mX - cursorPos.X, mY - cursorPos.Y);
             }

             // Iterate over the found windows and check if the current location is inside a window
             Point cursorPosition = Cursor.Position;
             selectedCaptureWindow = null;
             foreach (WindowDetails window in windows)
             {
            if (window.Contains(cursorPosition))
            {
               // Only go over the children if we are in window mode
               if (CaptureMode.Window == captureMode)
               {
                  selectedCaptureWindow = window.FindChildUnderPoint(cursorPosition);
               }
               else
               {
                  selectedCaptureWindow = window;
               }
               break;
            }
             }
             if (selectedCaptureWindow != null && !selectedCaptureWindow.Equals(lastWindow))
             {
            if (capture == null)
            {
               capture = new Capture();
            }
            capture.CaptureDetails.Title = selectedCaptureWindow.Text;
            capture.CaptureDetails.AddMetaData("windowtitle", selectedCaptureWindow.Text);
            if (captureMode == CaptureMode.Window)
            {
               // Here we want to capture the window which is under the mouse
               captureRect = selectedCaptureWindow.ClientRectangle;
               // As the ClientRectangle is not in Bitmap coordinates, we need to correct.
               captureRect.Offset(-capture.ScreenBounds.Location.X, -capture.ScreenBounds.Location.Y);
            }
             }
             if (mouseDown && (CaptureMode.Window != captureMode))
             {
            int x1 = Math.Min(mX, lastPos.X);
            int x2 = Math.Max(mX, lastPos.X);
            int y1 = Math.Min(mY, lastPos.Y);
            int y2 = Math.Max(mY, lastPos.Y);
            x1 = Math.Min(x1, cursorPos.X);
            x2 = Math.Max(x2, cursorPos.X);
            y1 = Math.Min(y1, cursorPos.Y);
            y2 = Math.Max(y2, cursorPos.Y);

            // Safety correction
            x2 += 2;
            y2 += 2;

            // Here we correct for text-size

            // Calculate the size
            int textForWidth = Math.Max(Math.Abs(mX - cursorPos.X), Math.Abs(mX - lastPos.X));
            int textForHeight = Math.Max(Math.Abs(mY - cursorPos.Y), Math.Abs(mY - lastPos.Y));

            using (Font rulerFont = new Font(FontFamily.GenericSansSerif, 8))
            {
               Size measureWidth = TextRenderer.MeasureText(textForWidth.ToString(), rulerFont);
               x1 -= measureWidth.Width + 15;

               Size measureHeight = TextRenderer.MeasureText(textForHeight.ToString(), rulerFont);
               y1 -= measureWidth.Height + 10;
            }
            Rectangle invalidateRectangle = new Rectangle(x1, y1, x2 - x1, y2 - y1);
            pictureBox.Invalidate(invalidateRectangle);
             }
             else
             {
            if (captureMode == CaptureMode.Window)
            {
               if (selectedCaptureWindow != null && !selectedCaptureWindow.Equals(lastWindow))
               {
                  // Using a 50 Pixel offset to the left, top, to make sure the text is invalidated too
                  const int SAFETY_SIZE = 50;
                  Rectangle invalidateRectangle = new Rectangle(lastCaptureRect.Location, lastCaptureRect.Size);
                  invalidateRectangle.X -= SAFETY_SIZE / 2;
                  invalidateRectangle.Y -= SAFETY_SIZE / 2;
                  invalidateRectangle.Width += SAFETY_SIZE;
                  invalidateRectangle.Height += SAFETY_SIZE;
                  pictureBox.Invalidate(invalidateRectangle);
                  invalidateRectangle = new Rectangle(captureRect.Location, captureRect.Size);
                  invalidateRectangle.X -= SAFETY_SIZE / 2;
                  invalidateRectangle.Y -= SAFETY_SIZE / 2;
                  invalidateRectangle.Width += SAFETY_SIZE;
                  invalidateRectangle.Height += SAFETY_SIZE;
                  pictureBox.Invalidate(invalidateRectangle);
               }
               if (capture.CaptureDetails.CaptureMode == CaptureMode.Video)
               {
                  pictureBox.Invalidate(new Rectangle(cursorPos.X + 20, cursorPos.Y + 20, 20, 20));
                  pictureBox.Invalidate(new Rectangle(lastPos.X + 20, lastPos.Y + 20, 20, 20));
               }
            }
            else
            {
               if (verticalMove)
               {
                  Rectangle before = GuiRectangle.GetGuiRectangle(0, lastPos.Y - 2, this.Width + 2, 45);
                  Rectangle after = GuiRectangle.GetGuiRectangle(0, cursorPos.Y - 2, this.Width + 2, 45);
                  pictureBox.Invalidate(before);
                  pictureBox.Invalidate(after);
               }
               if (horizontalMove)
               {
                  Rectangle before = GuiRectangle.GetGuiRectangle(lastPos.X - 2, 0, 75, this.Height + 2);
                  Rectangle after = GuiRectangle.GetGuiRectangle(cursorPos.X - 2, 0, 75, this.Height + 2);
                  pictureBox.Invalidate(before);
                  pictureBox.Invalidate(after);
               }
            }
             }
        }
示例#41
0
		/// <summary>
		/// This method will use User32 code to capture the specified captureBounds from the screen
		/// </summary>
		/// <param name="capture">ICapture where the captured Bitmap will be stored</param>
		/// <param name="captureBounds">Rectangle with the bounds to capture</param>
		/// <returns>A Capture Object with a part of the Screen as an Image</returns>
		public static ICapture CaptureRectangleFromDesktopScreen(ICapture capture, Rectangle captureBounds) {
			if (capture == null) {
				capture = new Capture();
			}
			capture.Image = CaptureRectangle(captureBounds);
			capture.Location = captureBounds.Location;
			return capture.Image == null ? null : capture;
		}
示例#42
0
        /// <summary>
        /// Capture the actual page (document)
        /// </summary>
        /// <param name="documentContainer">The document wrapped in a container</param>
        /// <returns>Bitmap with the page content as an image</returns>
        private static Bitmap capturePage(DocumentContainer documentContainer, ICapture capture)
        {
            WindowDetails contentWindowDetails = documentContainer.ContentWindow;
            // Calculate the page size
            int pageWidth = documentContainer.ScrollWidth;
            int pageHeight = documentContainer.ScrollHeight;

            // Here we loop over all the frames and try to make sure they don't overlap
            bool movedFrame;
            do {
                movedFrame = false;
                foreach(DocumentContainer currentFrame in documentContainer.Frames) {
                    foreach(DocumentContainer otherFrame in documentContainer.Frames) {
                        if (otherFrame.ID == currentFrame.ID) {
                            continue;
                        }
                        // check if we need to move
                        if (otherFrame.DestinationRectangle.IntersectsWith(currentFrame.DestinationRectangle) && !otherFrame.SourceRectangle.IntersectsWith(currentFrame.SourceRectangle)) {
                            bool horizalResize = currentFrame.SourceSize.Width < currentFrame.DestinationSize.Width;
                            bool verticalResize = currentFrame.SourceSize.Width < currentFrame.DestinationSize.Width;
                            bool horizalMove = currentFrame.SourceLeft < currentFrame.DestinationLeft;
                            bool verticalMove = currentFrame.SourceTop < currentFrame.DestinationTop;
                            bool leftOf = currentFrame.SourceRight <= otherFrame.SourceLeft;
                            bool belowOf = currentFrame.SourceBottom <= otherFrame.SourceTop;

                            if ((horizalResize || horizalMove) && leftOf) {
                                // Current frame resized horizontally, so move other horizontally
                                LOG.DebugFormat("Moving Frame {0} horizontally to the right of {1}", otherFrame.Name, currentFrame.Name);
                                otherFrame.DestinationLeft = currentFrame.DestinationRight;
                                movedFrame = true;
                            } else if ((verticalResize || verticalMove) && belowOf){
                                // Current frame resized vertically, so move other vertically
                                LOG.DebugFormat("Moving Frame {0} vertically to the bottom of {1}", otherFrame.Name, currentFrame.Name);
                                otherFrame.DestinationTop = currentFrame.DestinationBottom;
                                movedFrame = true;
                            } else {
                                LOG.DebugFormat("Frame {0} intersects with {1}", otherFrame.Name, currentFrame.Name);
                            }
                        }
                    }
                }
            } while(movedFrame);

            bool movedMouse = false;
            // Correct cursor location to be inside the window
            capture.MoveMouseLocation(-documentContainer.ContentWindow.Location.X, -documentContainer.ContentWindow.Location.Y);
            // See if the page has the correct size, as we capture the full frame content AND might have moved them
            // the normal pagesize will no longer be enough
            foreach(DocumentContainer frameData in documentContainer.Frames) {
                if (!movedMouse && frameData.SourceRectangle.Contains(capture.CursorLocation)) {
                    // Correct mouse cursor location for scrolled position (so it shows on the capture where it really was)
                    capture.MoveMouseLocation(frameData.ScrollLeft, frameData.ScrollTop);
                    movedMouse = true;
                    // Apply any other offset changes
                    int offsetX = frameData.DestinationLocation.X - frameData.SourceLocation.X;
                    int offsetY = frameData.DestinationLocation.Y - frameData.SourceLocation.Y;
                    capture.MoveMouseLocation(offsetX, offsetY);
                }

                //Get Frame Width & Height
                pageWidth = Math.Max(pageWidth, frameData.DestinationRight);
                pageHeight = Math.Max(pageHeight, frameData.DestinationBottom);
            }

            // If the mouse hasn't been moved, it wasn't on a frame. So correct the mouse according to the scroll position of the document
            if (!movedMouse) {
                // Correct mouse cursor location
                capture.MoveMouseLocation(documentContainer.ScrollLeft, documentContainer.ScrollTop);
            }

            // Limit the size as the editor currently can't work with sizes > short.MaxValue
            if (pageWidth > short.MaxValue) {
                LOG.WarnFormat("Capture has a width of {0} which bigger than the maximum supported {1}, cutting width to the maxium.", pageWidth, short.MaxValue);
                pageWidth = Math.Min(pageWidth, short.MaxValue);
            }
            if (pageHeight > short.MaxValue) {
                LOG.WarnFormat("Capture has a height of {0} which bigger than the maximum supported {1}, cutting height to the maxium", pageHeight, short.MaxValue);
                pageHeight = Math.Min(pageHeight, short.MaxValue);
            }

            //Create a target bitmap to draw into with the calculated page size
            Bitmap returnBitmap = new Bitmap(pageWidth, pageHeight, PixelFormat.Format24bppRgb);
            using (Graphics graphicsTarget = Graphics.FromImage(returnBitmap)) {
                // Clear the target with the backgroundcolor
                Color clearColor = documentContainer.BackgroundColor;
                LOG.DebugFormat("Clear color: {0}", clearColor);
                graphicsTarget.Clear(clearColor);

                // Get the base document & draw it
                drawDocument(documentContainer, contentWindowDetails, graphicsTarget);
                //ParseElements(documentContainer, graphicsTarget, returnBitmap);
                // Loop over the frames and clear their source area so we don't see any artefacts
                foreach(DocumentContainer frameDocument in documentContainer.Frames) {
                    using(Brush brush = new SolidBrush(clearColor)) {
                        graphicsTarget.FillRectangle(brush, frameDocument.SourceRectangle);
                    }
                }
                // Loop over the frames and capture their content
                foreach(DocumentContainer frameDocument in documentContainer.Frames) {
                    drawDocument(frameDocument, contentWindowDetails, graphicsTarget);
                    //ParseElements(frameDocument, graphicsTarget, returnBitmap);
                }
            }
            return returnBitmap;
        }
示例#43
0
		/// <summary>
		/// This method will use User32 code to capture the specified captureBounds from the screen
		/// </summary>
		/// <param name="capture">ICapture where the captured Bitmap will be stored</param>
		/// <param name="captureBounds">Rectangle with the bounds to capture</param>
		/// <returns>A Capture Object with a part of the Screen as an Image</returns>
		public static ICapture CaptureRectangle(ICapture capture, Rectangle captureBounds) {
			if (capture == null) {
				capture = new Capture();
			}
			Image capturedImage = null;
			// If the CaptureHandler has a handle use this, otherwise use the CaptureRectangle here
			if (CaptureHandler.CaptureScreenRectangle != null) {
				try {
					capturedImage = CaptureHandler.CaptureScreenRectangle(captureBounds);
				} catch {
				}
			}
			// If no capture, use the normal screen capture
			if  (capturedImage == null) {
				capturedImage = CaptureRectangle(captureBounds);
			}
			capture.Image = capturedImage;
			capture.Location = captureBounds.Location;
			return capture.Image == null ? null : capture;
		}
示例#44
0
		/// <summary>
		/// This method will call the CaptureRectangle with the screenbounds, therefor Capturing the whole screen.
		/// </summary>
		/// <returns>A Capture Object with the Screen as an Image</returns>
		public static ICapture CaptureScreen(ICapture capture) {
			if (capture == null) {
				capture = new Capture();
			}
			return CaptureRectangle(capture, capture.ScreenBounds);
		}
示例#45
0
文件: Form1.cs 项目: haivido/Vido
 void capture2_NewFrame(ICapture sender, NewFrameEventArgs e)
 {
     pictureBox2.Image = e.Bitmap;
 }
示例#46
-1
		/// <summary>
		/// This creates the capture form
		/// </summary>
		/// <param name="capture"></param>
		/// <param name="windows"></param>
		public CaptureForm(ICapture capture, List<WindowDetails> windows) {
			if (_currentForm != null) {
				LOG.Warn("Found currentForm, Closing already opened CaptureForm");
				_currentForm.Close();
				_currentForm = null;
				Application.DoEvents();
			}
			_currentForm = this;

			// Enable the AnimatingForm
			EnableAnimation = true;

			// clean up
			FormClosed += ClosedHandler;

			_capture = capture;
			_windows = windows;
			_captureMode = capture.CaptureDetails.CaptureMode;

			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			// Only double-buffer when we are not in a TerminalServerSession
			DoubleBuffered = !isTerminalServerSession;
			Text = "Greenshot capture form";

			// Make sure we never capture the captureform
			WindowDetails.RegisterIgnoreHandle(Handle);
			// Unregister at close
			FormClosing += ClosingHandler;

			// set cursor location
			_cursorPos = WindowCapture.GetCursorLocationRelativeToScreenBounds();

			// Initialize the animations, the window capture zooms out from the cursor to the window under the cursor 
			if (_captureMode == CaptureMode.Window) {
				_windowAnimator = new RectangleAnimator(new Rectangle(_cursorPos, Size.Empty), _captureRect, FramesForMillis(700), EasingType.Quintic, EasingMode.EaseOut);
			}

			// Set the zoomer animation
			InitializeZoomer(Conf.ZoomerEnabled);

			SuspendLayout();
			Bounds = capture.ScreenBounds;
			ResumeLayout();
			
			// Fix missing focus
			ToFront = true;
			TopMost = true;
		}
示例#47
-2
		/// <summary>
		/// This method will capture the current Cursor by using User32 Code
		/// </summary>
		/// <returns>A Capture Object with the Mouse Cursor information in it.</returns>
		public static ICapture CaptureCursor(ICapture capture) {
			LOG.Debug("Capturing the mouse cursor.");
			if (capture == null) {
				capture = new Capture();
			}
			int x,y;
			CursorInfo cursorInfo = new CursorInfo(); 
			IconInfo iconInfo;
			cursorInfo.cbSize = Marshal.SizeOf(cursorInfo);
			if (User32.GetCursorInfo(out cursorInfo)) {
				if (cursorInfo.flags == User32.CURSOR_SHOWING) { 
					using (SafeIconHandle safeIcon = User32.CopyIcon(cursorInfo.hCursor)) {
						if (User32.GetIconInfo(safeIcon, out iconInfo)) {
							Point cursorLocation = User32.GetCursorLocation();
							// Allign cursor location to Bitmap coordinates (instead of Screen coordinates)
							x = cursorLocation.X - iconInfo.xHotspot - capture.ScreenBounds.X;
							y = cursorLocation.Y - iconInfo.yHotspot - capture.ScreenBounds.Y;
							// Set the location
							capture.CursorLocation = new Point(x, y);
	
							using (Icon icon = Icon.FromHandle(safeIcon.DangerousGetHandle())) {
								capture.Cursor = icon;
							}
	
							if (iconInfo.hbmMask != IntPtr.Zero) {
								DeleteObject(iconInfo.hbmMask);
							}
							if (iconInfo.hbmColor != IntPtr.Zero) {
								DeleteObject(iconInfo.hbmColor);
							}
						}
					}
				}
			}
			return capture;
		}