예제 #1
0
 public static void CaptureIe(bool captureMouse, WindowDetails windowToCapture)
 {
     using (CaptureHelper captureHelper = new CaptureHelper(CaptureMode.IE, captureMouse)) {
         captureHelper.SelectedCaptureWindow = windowToCapture;
         captureHelper.MakeCapture();
     }
 }
예제 #2
0
		/// <summary>
		/// Show the thumbnail of the supplied window above (or under) the parent Control
		/// </summary>
		/// <param name="window">WindowDetails</param>
		/// <param name="parentControl">Control</param>
		public void ShowThumbnail(WindowDetails window, Control parentControl) {
			UnregisterThumbnail();

			DWM.DwmRegisterThumbnail(Handle, window.Handle, out thumbnailHandle);
			if (thumbnailHandle != IntPtr.Zero) {
				SIZE sourceSize;
				DWM.DwmQueryThumbnailSourceSize(thumbnailHandle, out sourceSize);
				int thumbnailHeight = 200;
				int thumbnailWidth = (int)(thumbnailHeight * ((float)sourceSize.width / (float)sourceSize.height));
				if (parentControl != null && thumbnailWidth > parentControl.Width) {
					thumbnailWidth = parentControl.Width;
					thumbnailHeight = (int)(thumbnailWidth * ((float)sourceSize.height / (float)sourceSize.width));
				}
				Width = thumbnailWidth;
				Height = thumbnailHeight;
				// Prepare the displaying of the Thumbnail
				DWM_THUMBNAIL_PROPERTIES props = new DWM_THUMBNAIL_PROPERTIES();
				props.Opacity = (byte)255;
				props.Visible = true;
				props.SourceClientAreaOnly = false;
				props.Destination = new RECT(0, 0, thumbnailWidth, thumbnailHeight);
				DWM.DwmUpdateThumbnailProperties(thumbnailHandle, ref props);
				if (parentControl != null) {
					AlignToControl(parentControl);
				}

				if (!Visible) {
					Show();
				}
				// Make sure it's on "top"!
				if (parentControl != null) {
					User32.SetWindowPos(Handle, parentControl.Handle, 0, 0, 0, 0, WindowPos.SWP_NOMOVE | WindowPos.SWP_NOSIZE | WindowPos.SWP_NOACTIVATE);
				}
			}
		}
예제 #3
0
 static OutlookDestination()
 {
     if (EmailConfigHelper.HasOutlook())
     {
         isActiveFlag = true;
     }
     exePath = PluginUtils.GetExePath("OUTLOOK.EXE");
     if (exePath != null && File.Exists(exePath))
     {
         applicationIcon = PluginUtils.GetExeIcon(exePath, 0);
         WindowDetails.AddProcessToExcludeFromFreeze("outlook");
         if (conf.OutlookAllowExportInMeetings)
         {
             meetingIcon = PluginUtils.GetExeIcon(exePath, 2);
         }
     }
     else
     {
         exePath = null;
     }
     if (exePath == null)
     {
         isActiveFlag = false;
     }
 }
        public static void CaptureWindow(WindowDetails windowToCapture)
        {
            CaptureHelper captureHelper = new CaptureHelper(CaptureMode.ActiveWindow);

            captureHelper.SelectedCaptureWindow = windowToCapture;
            captureHelper.MakeCapture();
        }
예제 #5
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, 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);
        }
예제 #6
0
        private DocumentContainer(IHTMLWindow2 frameWindow, WindowDetails contentWindow, DocumentContainer parent)
        {
            //IWebBrowser2 webBrowser2 = frame as IWebBrowser2;
            //IHTMLDocument2 document2 = webBrowser2.Document as IHTMLDocument2;
            IHTMLDocument2 document2 = GetDocumentFromWindow(frameWindow);

            try {
                LOG.DebugFormat("frameWindow.name {0}", frameWindow.name);
                name = frameWindow.name;
            } catch {
            }
            try {
                LOG.DebugFormat("document2.url {0}", document2.url);
            } catch {
            }
            try {
                LOG.DebugFormat("document2.title {0}", document2.title);
            } catch {
            }

            this.parent = parent;
            // Calculate startLocation for the frames
            IHTMLWindow2 window2 = document2.parentWindow;
            IHTMLWindow3 window3 = (IHTMLWindow3)window2;
            Point        contentWindowLocation = contentWindow.WindowRectangle.Location;
            int          x = window3.screenLeft - contentWindowLocation.X;
            int          y = window3.screenTop - contentWindowLocation.Y;

            // Release IHTMLWindow 2+3 com objects
            releaseCom(window2);
            releaseCom(window3);

            startLocation = new Point(x, y);
            Init(document2, contentWindow);
        }
예제 #7
0
 /// <summary>
 /// Insert image from supplied tmp file into the give excel workbook
 /// </summary>
 /// <param name="workbookName"></param>
 /// <param name="tmpFile"></param>
 /// <param name="imageSize"></param>
 public static void InsertIntoExistingWorkbook(string workbookName, string tmpFile, Size imageSize)
 {
     using (IExcelApplication excelApplication = GetExcelApplication()) {
         if (excelApplication == null)
         {
             return;
         }
         using (IWorkbooks workbooks = excelApplication.Workbooks) {
             for (int i = 1; i <= workbooks.Count; i++)
             {
                 using (IWorkbook workbook = workbooks[i]) {
                     if (workbook != null && workbook.Name.StartsWith(workbookName))
                     {
                         InsertIntoExistingWorkbook(workbook, tmpFile, imageSize);
                     }
                 }
             }
         }
         int hWnd = excelApplication.Hwnd;
         if (hWnd > 0)
         {
             WindowDetails.ToForeground(new IntPtr(hWnd));
         }
     }
 }
예제 #8
0
        /// <summary>
        /// Find the DirectUI window for MSAA (Accessible)
        /// </summary>
        /// <param name="browserWindowDetails">The browser WindowDetails</param>
        /// <returns>WindowDetails for the DirectUI window</returns>
        public static WindowDetails GetDirectUI(WindowDetails browserWindowDetails)
        {
            if (browserWindowDetails == null)
            {
                return(null);
            }
            WindowDetails tmpWD = browserWindowDetails;

            // Since IE 9 the TabBandClass is less deep!
            if (IEVersion() < 9)
            {
                tmpWD = tmpWD.GetChild("CommandBarClass");
                if (tmpWD != null)
                {
                    tmpWD = tmpWD.GetChild("ReBarWindow32");
                }
            }
            if (tmpWD != null)
            {
                tmpWD = tmpWD.GetChild("TabBandClass");
            }
            if (tmpWD != null)
            {
                tmpWD = tmpWD.GetChild("DirectUIHWND");
            }
            return(tmpWD);
        }
        /// <summary>
        /// Return an IEnumerable with the currently opened IE urls
        /// </summary>
        /// <returns></returns>
        public static IEnumerable <string> GetIEUrls()
        {
            List <string> urls = new List <string>();

            // Find the IE window
            foreach (WindowDetails ieWindow in WindowDetails.GetAllWindows("IEFrame"))
            {
                WindowDetails directUIWD = GetDirectUI(ieWindow);
                if (directUIWD != null)
                {
                    Accessible    ieAccessible = new Accessible(directUIWD.Handle);
                    List <string> ieUrls       = ieAccessible.IETabUrls;
                    if (ieUrls != null && ieUrls.Count > 0)
                    {
                        foreach (string url in ieUrls)
                        {
                            if (!urls.Contains(url))
                            {
                                urls.Add(url);
                            }
                        }
                    }
                }
            }

            return(urls);
        }
예제 #10
0
        /// <summary>
        /// Handle the WinEvent
        /// </summary>
        /// <param name="hWinEventHook">The Hook IntPtr</param>
        /// <param name="eventType">Event Type to handle, enum WinEvent</param>
        /// <param name="hwnd">Window handle which caused the event</param>
        /// <param name="idObject">Object ID, enum EventObjects</param>
        /// <param name="idChild">Child ID of the window</param>
        /// <param name="dwEventThread">Thread which generated the ID</param>
        /// <param name="dwmsEventTime"></param>
        private static void WinEventProc(IntPtr hWinEventHook, WinEvent eventType, IntPtr hwnd, EventObjects idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
        {
            // Check if it's an event generated by a Window
            if (hwnd == IntPtr.Zero || idObject != EventObjects.OBJID_WINDOW)
            {
                // Other events do not interest us.
                return;
            }
            String classname = null;

            // Check if the event was generated by the OLE Event Thread, which causes a lot of create/destroy
            if (oleEventThread != 0 && dwEventThread == oleEventThread)
            {
                return;
            }

            // Only get the classname when it's not a destroy (classname is not available)
            if (eventType == WinEvent.EVENT_OBJECT_CREATE)
            {
                classname = WindowDetails.GetClassName(hwnd);
                // Make sure the OleMainThreadWndClass events are ignored.
                if (oleEventThread == 0)
                {
                    if (classname == "OleMainThreadWndClass")
                    {
                        oleEventThread = dwEventThread;
                        return;
                    }
                }
            }

            LOG.DebugFormat("eventType={0},hwnd={1},classname={4},idObject={2},idChild={3},dwEventThread={5}", eventType, hwnd, idObject, idChild, classname, dwEventThread);
        }
예제 #11
0
        public ImageEditorForm(ISurface iSurface, bool outputMade)
        {
            editorList.Add(this);

            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            ManualLanguageApply = true;
            InitializeComponent();

            Shown += delegate
            {
                // Make sure the editor is placed on the same location as the last editor was on close
                WindowDetails thisForm = new WindowDetails(Handle);
                thisForm.WindowPlacement = editorConfiguration.GetEditorPlacement();
            };

            // init surface
            Surface = iSurface;
            // Intial "saved" flag for asking if the image needs to be save
            surface.Modified = !outputMade;

            updateUI();

            // Workaround: As the cursor is (mostly) selected on the surface a funny artifact is visible, this fixes it.
            //hideToolstripItems();
        }
예제 #12
0
 /// <summary>
 /// Simple check if IE is running
 /// </summary>
 /// <returns>bool</returns>
 public static bool IsIERunning()
 {
     foreach (WindowDetails shellWindow in WindowDetails.GetAllWindows("IEFrame"))
     {
         return(true);
     }
     return(false);
 }
예제 #13
0
 /// <summary>
 /// Make sure the form is visible, if this is wanted
 /// </summary>
 /// <param name="e">EventArgs</param>
 protected override void OnShown(EventArgs e)
 {
     base.OnShown(e);
     if (ToFront)
     {
         WindowDetails.ToForeground(Handle);
     }
 }
        /// <summary>
        /// Gets a list of all IE Windows & tabs with the captions of the instances
        /// </summary>
        /// <returns>List<KeyValuePair<WindowDetails, string>></returns>
        public static List <KeyValuePair <WindowDetails, string> > GetBrowserTabs()
        {
            List <IntPtr> ieHandleList = new List <IntPtr>();
            Dictionary <WindowDetails, List <string> > browserWindows = new Dictionary <WindowDetails, List <string> >();

            // Find the IE windows
            foreach (WindowDetails ieWindow in GetIEWindows())
            {
                try {
                    if (!ieHandleList.Contains(ieWindow.Handle))
                    {
                        if ("IEFrame".Equals(ieWindow.ClassName))
                        {
                            WindowDetails directUIWD = IEHelper.GetDirectUI(ieWindow);
                            if (directUIWD != null)
                            {
                                Accessible accessible = new Accessible(directUIWD.Handle);
                                browserWindows.Add(ieWindow, accessible.IETabCaptions);
                            }
                        }
                        else if (configuration.WindowClassesToCheckForIE != null && configuration.WindowClassesToCheckForIE.Contains(ieWindow.ClassName))
                        {
                            List <string> singleWindowText = new List <string>();
                            try {
                                IHTMLDocument2 document2 = getHTMLDocument(ieWindow);
                                string         title     = document2.title;
                                Marshal.ReleaseComObject(document2);
                                if (string.IsNullOrEmpty(title))
                                {
                                    singleWindowText.Add(ieWindow.Text);
                                }
                                else
                                {
                                    singleWindowText.Add(ieWindow.Text + " - " + title);
                                }
                            } catch {
                                singleWindowText.Add(ieWindow.Text);
                            }
                            browserWindows.Add(ieWindow, singleWindowText);
                        }
                        ieHandleList.Add(ieWindow.Handle);
                    }
                } catch (Exception) {
                    LOG.Warn("Can't get Info from " + ieWindow.ClassName);
                }
            }

            List <KeyValuePair <WindowDetails, string> > returnList = new List <KeyValuePair <WindowDetails, string> >();

            foreach (WindowDetails windowDetails in browserWindows.Keys)
            {
                foreach (string tab in browserWindows[windowDetails])
                {
                    returnList.Add(new KeyValuePair <WindowDetails, string>(windowDetails, tab));
                }
            }
            return(returnList);
        }
예제 #15
0
		/// <summary>
		/// Does the supplied window have a IE part?
		/// </summary>
		/// <param name="someWindow"></param>
		/// <returns></returns>
		public static bool IsIEWindow(WindowDetails someWindow) {
			if ("IEFrame".Equals(someWindow.ClassName)) {
				return true;
			}
			if (configuration.WindowClassesToCheckForIE != null && configuration.WindowClassesToCheckForIE.Contains(someWindow.ClassName)) {
				return someWindow.GetChild("Internet Explorer_Server") != null;
			}
			return false;
		}
예제 #16
0
 private BugReportForm()
 {
     //
     // The InitializeComponent() call is required for Windows Forms designer support.
     //
     InitializeComponent();
     this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon();
     WindowDetails.ToForeground(this.Handle);
 }
예제 #17
0
 private BugReportForm()
 {
     //
     // The InitializeComponent() call is required for Windows Forms designer support.
     //
     InitializeComponent();
     lang = Language.GetInstance();
     UpdateUI();
     WindowDetails.ToForeground(this.Handle);
 }
예제 #18
0
        public SpyFormHandler(IntPtr incomingHandler)
        {
            InstanceCounter.Instance.Increment();

            _spyHandler = incomingHandler;
            window      = new WindowDetails(_spyHandler);
            pen         = new Pen(Settings.Default.DefaultColor);

            InitializeComponent();
        }
 // Helper method to activate a certain IE Tab
 public static void ActivateIETab(WindowDetails ieWindowDetails, int tabIndex)
 {
     WindowDetails directUIWindowDetails = IEHelper.GetDirectUI(ieWindowDetails);
     // Bring window to the front
     ieWindowDetails.Restore();
     // Get accessible
     Accessible ieAccessible = new Accessible(directUIWindowDetails.Handle);
     // Activate Tab
     ieAccessible.ActivateIETab(tabIndex);
 }
예제 #20
0
        private void FindProcessToolStripMenuItem_DropDownClosed(object sender, EventArgs e)
        {
            UnregisterThumbnail();

            if (oldWindow != null)
            {
                window = new WindowDetails(oldWindow.Handle);
                ShowThumbnail();
            }
        }
        private void CaptureWithFeedback()
        {
            using (CaptureForm captureForm = new CaptureForm(capture, windows))
            {
                DialogResult result = captureForm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    selectedCaptureWindow = captureForm.SelectedCaptureWindow;
                    captureRect           = captureForm.CaptureRectangle;
                    // Get title
                    if (selectedCaptureWindow != null)
                    {
                        capture.CaptureDetails.Title = selectedCaptureWindow.Text;
                    }

                    // Experimental code
                    if (capture.CaptureDetails.CaptureMode == CaptureMode.Video)
                    {
                        if (captureForm.UsedCaptureMode == CaptureMode.Window)
                        {
                            screenCapture = new ScreenCaptureHelper(selectedCaptureWindow);
                        }
                        else if (captureForm.UsedCaptureMode == CaptureMode.Region)
                        {
                            screenCapture = new ScreenCaptureHelper(captureRect);
                        }
                        if (screenCapture != null)
                        {
                            screenCapture.RecordMouse = capture.CursorVisible;
                            if (screenCapture.Start(25))
                            {
                                return;
                            }
                            // User clicked cancel or a problem occured
                            screenCapture.Stop();
                            screenCapture = null;
                            return;
                        }
                    }

                    if (captureRect.Height > 0 && captureRect.Width > 0)
                    {
                        if (windowDetailsThread != null)
                        {
                            windowDetailsThread.Join();
                        }
                        // 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;
                        HandleCapture();
                    }
                }
            }
        }
예제 #22
0
        public static IEnumerable <string> GetBrowserUrls()
        {
            // FireFox
            foreach (WindowDetails window in WindowDetails.GetAllWindows("MozillaWindowClass"))
            {
                if (window.Text.Length == 0)
                {
                    continue;
                }
                AutomationElement currentElement  = AutomationElement.FromHandle(window.Handle);
                Condition         conditionCustom = new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom), new PropertyCondition(AutomationElement.IsOffscreenProperty, false));
                for (int i = 5; i > 0 && currentElement != null; i--)
                {
                    currentElement = currentElement.FindFirst(TreeScope.Children, conditionCustom);
                }
                if (currentElement == null)
                {
                    continue;
                }

                Condition         conditionDocument = new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document), new PropertyCondition(AutomationElement.IsOffscreenProperty, false));
                AutomationElement docElement        = currentElement.FindFirst(TreeScope.Children, conditionDocument);
                if (docElement == null)
                {
                    continue;
                }
                foreach (AutomationPattern pattern in docElement.GetSupportedPatterns())
                {
                    if (pattern.ProgrammaticName != "ValuePatternIdentifiers.Pattern")
                    {
                        continue;
                    }
                    string url = (docElement.GetCurrentPattern(pattern) as ValuePattern).Current.Value.ToString();
                    if (!string.IsNullOrEmpty(url))
                    {
                        yield return(url);

                        break;
                    }
                }
            }

            foreach (WindowDetails window in WindowDetails.GetAllWindows("MozillaWindowClass"))
            {
                if (window.Text.Length == 0)
                {
                    continue;
                }
                AutomationElement currentElement = AutomationElement.FromHandle(window.Handle);
            }
            foreach (string url in IEHelper.GetIEUrls())
            {
                yield return(url);
            }
        }
        /// <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.Debug("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
            WindowDetails.ToForeground(Handle);
            TopMost = true;
        }
예제 #24
0
 static ExcelDestination()
 {
     ExePath = PluginUtils.GetExePath("EXCEL.EXE");
     if (ExePath != null && File.Exists(ExePath))
     {
         WindowDetails.AddProcessToExcludeFromFreeze("excel");
     }
     else
     {
         ExePath = null;
     }
 }
예제 #25
0
        // Helper method to activate a certain IE Tab
        public static void ActivateIETab(WindowDetails ieWindowDetails, int tabIndex)
        {
            WindowDetails directUIWindowDetails = GetDirectUI(ieWindowDetails);

            // Bring window to the front
            ieWindowDetails.Restore();
            // Get accessible
            Accessible ieAccessible = new Accessible(directUIWindowDetails.Handle);

            // Activate Tab
            ieAccessible.ActivateIETab(tabIndex);
        }
 static PowerpointDestination()
 {
     exePath = PluginUtils.GetExePath("POWERPNT.EXE");
     if (exePath != null && File.Exists(exePath))
     {
         WindowDetails.AddProcessToExcludeFromFreeze("powerpnt");
     }
     else
     {
         exePath = null;
     }
 }
예제 #27
0
 static OneNoteDestination()
 {
     exePath = PluginUtils.GetExePath("ONENOTE.EXE");
     if (exePath != null && File.Exists(exePath))
     {
         WindowDetails.AddProcessToExcludeFromFreeze("onenote");
     }
     else
     {
         exePath = null;
     }
 }
예제 #28
0
 /// <summary>
 /// Does the supplied window have a IE part?
 /// </summary>
 /// <param name="someWindow"></param>
 /// <returns></returns>
 public static bool IsIEWindow(WindowDetails someWindow)
 {
     if ("IEFrame".Equals(someWindow.ClassName))
     {
         return(true);
     }
     if (configuration.WindowClassesToCheckForIE != null && configuration.WindowClassesToCheckForIE.Contains(someWindow.ClassName))
     {
         return(someWindow.GetChild("Internet Explorer_Server") != null);
     }
     return(false);
 }
예제 #29
0
		/// <summary>
		/// Return true if the supplied window has a sub-window which covers more than the supplied percentage
		/// </summary>
		/// <param name="someWindow">WindowDetails to check</param>
		/// <param name="minimumPercentage">min percentage</param>
		/// <returns></returns>
		public static bool IsMostlyIEWindow(WindowDetails someWindow, int minimumPercentage) {
			WindowDetails ieWindow = someWindow.GetChild("Internet Explorer_Server");
			if (ieWindow != null) {
				Rectangle wholeClient = someWindow.ClientRectangle;
				Rectangle partClient = ieWindow.ClientRectangle;
				int percentage = (int)(100*((float)(partClient.Width * partClient.Height)) / ((float)(wholeClient.Width * wholeClient.Height)));
				LOG.InfoFormat("Window {0}, ie part {1}, percentage {2}", wholeClient, partClient, percentage);
				if (percentage > minimumPercentage) {
					return true;
				}
			}
			return false;
		}
예제 #30
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();
			}
		}
예제 #31
0
        private void ShowThumbnailOnEnter(object sender, EventArgs e)
        {
            ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem;

            if (toolStripMenuItem != null)
            {
                window = toolStripMenuItem.Tag as WindowDetails;

                handler = window.Handle;

                ShowThumbnail();
            }
        }
예제 #32
0
 static ExcelDestination()
 {
     exePath = PluginUtils.GetExePath("EXCEL.EXE");
     if (exePath != null && File.Exists(exePath))
     {
         applicationIcon = PluginUtils.GetExeIcon(exePath, 0);
         workbookIcon    = PluginUtils.GetExeIcon(exePath, 1);
         WindowDetails.AddProcessToExcludeFromFreeze("excel");
     }
     else
     {
         exePath = null;
     }
 }
예제 #33
0
        /// <summary>
        /// Helper Method for creating an Email with Image Attachment
        /// </summary>
        /// <param name="image">The image to send</param>
        /// <param name="captureDetails">ICaptureDetails</param>
        public static void SendImage(ISurface surface, ICaptureDetails captureDetails)
        {
            string tmpFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings());

            if (tmpFile != null)
            {
                // Store the list of currently active windows, so we can make sure we show the email window later!
                List <WindowDetails> windowsBefore = WindowDetails.GetVisibleWindows();
                // Fallback to MAPI
                // Send the email
                SendImage(tmpFile, captureDetails);
                WindowDetails.ActiveNewerWindows(windowsBefore);
            }
        }
예제 #34
0
        void Contextmenu_window_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;

            try
            {
                WindowDetails windowToCapture = (WindowDetails)clickedItem.Tag;
                captureForm.MakeCapture(windowToCapture);
            }
            catch (Exception exception)
            {
                LOG.Error(exception);
            }
        }
예제 #35
0
 /// <summary>
 /// Return an IEnumerable with the currently opened IE urls
 /// </summary>
 /// <returns></returns>
 public static IEnumerable <string> GetIEUrls()
 {
     // Find the IE window
     foreach (WindowDetails ieWindow in WindowDetails.GetAllWindows("IEFrame"))
     {
         WindowDetails directUIWD = GetDirectUI(ieWindow);
         if (directUIWD != null)
         {
             Accessible ieAccessible = new Accessible(directUIWD.Handle);
             foreach (string url in ieAccessible.IETabUrls)
             {
                 yield return(url);
             }
         }
     }
 }
예제 #36
0
        public OAuthLoginForm(string browserTitle, Size size, string authorizationLink, string callbackUrl)
        {
            this.callbackUrl = callbackUrl;
            InitializeComponent();
            this.ClientSize          = size;
            this.Icon                = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon();
            this.Text                = browserTitle;
            this.addressTextBox.Text = authorizationLink;

            // The script errors are suppressed by using the ExtendedWebBrowser
            browser.ScriptErrorsSuppressed = false;
            browser.DocumentCompleted     += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
            browser.Navigate(new Uri(authorizationLink));

            WindowDetails.ToForeground(this.Handle);
        }
예제 #37
0
 /// <summary>
 /// Find the DirectUI window for MSAA (Accessible)
 /// </summary>
 /// <param name="browserWindowDetails">The browser WindowDetails</param>
 /// <returns>WindowDetails for the DirectUI window</returns>
 public static WindowDetails GetDirectUI(WindowDetails browserWindowDetails)
 {
     WindowDetails tmpWD = browserWindowDetails;
     // Since IE 9 the TabBandClass is less deep!
     if (IEHelper.IEVersion() < 9) {
         tmpWD = tmpWD.GetChild("CommandBarClass");
         if (tmpWD != null) {
             tmpWD = tmpWD.GetChild("ReBarWindow32");
         }
     }
     if (tmpWD != null) {
         tmpWD = tmpWD.GetChild("TabBandClass");
     }
     if (tmpWD != null) {
         tmpWD = tmpWD.GetChild("DirectUIHWND");
     }
     return tmpWD;
 }
예제 #38
0
        private DocumentContainer(IHTMLWindow2 frameWindow, WindowDetails contentWindow, DocumentContainer parent)
        {
            //IWebBrowser2 webBrowser2 = frame as IWebBrowser2;
            //IHTMLDocument2 document2 = webBrowser2.Document as IHTMLDocument2;
            IHTMLDocument2 document2 = GetDocumentFromWindow(frameWindow);
            try {
                LOG.DebugFormat("frameWindow.name {0}", frameWindow.name);
            } catch {

            }
            try {
                LOG.DebugFormat("document2.url {0}",document2.url);
            } catch {

            }
            try {
                LOG.DebugFormat("document2.title {0}", document2.title);
            } catch {

            }

            this.parent = parent;
            // Calculate startLocation for the frames
            IHTMLWindow3 window3 = (IHTMLWindow3)document2.parentWindow;
            //			IHTMLElement element = window2.document.body;
            //			long x = 0;
            //			long y = 0;
            //			do {
            //				x += element.offsetLeft;
            //				y += element.offsetTop;
            //				element = element.offsetParent;
            //			} while (element != null);
            //			startLocation = new Point((int)x, (int)y);
            Point contentWindowLocation = contentWindow.ClientRectangle.Location;
            int x = window3.screenLeft - contentWindowLocation.X;
            int y = window3.screenTop - contentWindowLocation.Y;
            startLocation = new Point(x, y);
            Init(document2, contentWindow);
        }
예제 #39
0
		private DocumentContainer(IHTMLWindow2 frameWindow, WindowDetails contentWindow, DocumentContainer parent) {
			//IWebBrowser2 webBrowser2 = frame as IWebBrowser2;
			//IHTMLDocument2 document2 = webBrowser2.Document as IHTMLDocument2;
			IHTMLDocument2 document2 = GetDocumentFromWindow(frameWindow);
			try {
				LOG.DebugFormat("frameWindow.name {0}", frameWindow.name);
				name = frameWindow.name;
			} catch {
				
			}
			try {
				LOG.DebugFormat("document2.url {0}",document2.url);
			} catch {
				
			}
			try {
				LOG.DebugFormat("document2.title {0}", document2.title);
			} catch {
				
			}

			this.parent = parent;
			// Calculate startLocation for the frames
			IHTMLWindow2 window2 = document2.parentWindow;
			IHTMLWindow3 window3 = (IHTMLWindow3)window2;
			Point contentWindowLocation = contentWindow.WindowRectangle.Location;
			int x = window3.screenLeft - contentWindowLocation.X;
			int y = window3.screenTop - contentWindowLocation.Y;

			// Release IHTMLWindow 2+3 com objects
			releaseCom(window2);
			releaseCom(window3);

			startLocation = new Point(x, y);
			Init(document2, contentWindow);
		}
예제 #40
0
        public ImageEditorForm(Surface surface, bool outputMade)
        {
            //
             // The InitializeComponent() call is required for Windows Forms designer support.
             //
             InitializeComponent();
             System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ImageEditorForm));
             Image backgroundForTransparency = (Image)resources.GetObject("checkerboard.Image");
             surface.TransparencyBackgroundBrush = new TextureBrush(backgroundForTransparency, WrapMode.Tile);
             // Make sure Double-buffer is enabled
             SetStyle(ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);

             // Intial "saved" flag for asking if the image needs to be save
             surface.Modified = !outputMade;

             // resizing the panel is futile, since it is docked. however, it seems
             // to fix the bug (?) with the vscrollbar not being able to shrink to
             // a smaller size than the initial panel size (as set by the forms designer)
             panel1.Height = 10;

             // init surface
             this.surface = surface;
             surface.TabStop = false;

             surface.MovingElementChanged += delegate { refreshEditorControls(); };
             surface.DrawingModeChanged += new SurfaceDrawingModeEventHandler(surface_DrawingModeChanged);
             surface.SurfaceSizeChanged += new SurfaceSizeChangeEventHandler(SurfaceSizeChanged);

             this.fontFamilyComboBox.PropertyChanged += new PropertyChangedEventHandler(FontPropertyChanged);

             surface.FieldAggregator.FieldChanged += new FieldChangedEventHandler(FieldAggregatorFieldChanged);
             obfuscateModeButton.DropDownItemClicked += FilterPresetDropDownItemClicked;
             highlightModeButton.DropDownItemClicked += FilterPresetDropDownItemClicked;

             panel1.Controls.Add(surface);

             lang = Language.GetInstance();

             // Make sure the editor is placed on the same location as the last editor was on close
             WindowDetails thisForm = new WindowDetails(this.Handle);
             thisForm.SetWindowPlacement(editorConfiguration.GetEditorPlacement());

             SurfaceSizeChanged(this.Surface);

             updateUI();
             IniConfig.IniChanged += new FileSystemEventHandler(ReloadConfiguration);

             bindFieldControls();
             refreshEditorControls();
             // Workaround: As the cursor is (mostly) selected on the surface a funny artifact is visible, this fixes it.
             hideToolstripItems();

             toolbarButtons = new ToolStripButton[] { btnCursor, btnRect, btnEllipse, btnText, btnLine, btnArrow, btnFreehand, btnHighlight, btnObfuscate, btnCrop };
             //toolbarDropDownButtons = new ToolStripDropDownButton[]{btnBlur, btnPixeliate, btnTextHighlighter, btnAreaHighlighter, btnMagnifier};

             PluginHelper.instance.CreateImageEditorOpenEvent(this);
             pluginToolStripMenuItem.Visible = pluginToolStripMenuItem.DropDownItems.Count > 0;

             emailToolStripMenuItem.Enabled = EmailConfigHelper.HasMAPI() || EmailConfigHelper.HasOutlook();

             // Workaround: for the MouseWheel event which doesn't get to the panel
             this.MouseWheel += new MouseEventHandler(PanelMouseWheel);
        }
        /// <summary>
        /// Helper method which will retrieve the IHTMLDocument2 for the supplied window,
        ///  or return the first if none is supplied.
        /// </summary>
        /// <param name="browserWindowDetails">The WindowDetails to get the IHTMLDocument2 for</param>
        /// <param name="document2">Ref to the IHTMLDocument2 to return</param>
        /// <returns>The WindowDetails to which the IHTMLDocument2 belongs</returns>
        private static DocumentContainer GetDocument(WindowDetails activeWindow)
        {
            DocumentContainer returnDocumentContainer = null;
            WindowDetails returnWindow = null;
            IHTMLDocument2 returnDocument2 = null;
            // alternative if no match
            WindowDetails alternativeReturnWindow = null;
            IHTMLDocument2 alternativeReturnDocument2 = null;

            // Find the IE window
            foreach (WindowDetails ieWindow in WindowDetails.GetAllWindows("IEFrame")) {
                LOG.DebugFormat("Processing {0} - {1}", ieWindow.ClassName, ieWindow.Text);

                Accessible ieAccessible = null;
                WindowDetails directUIWD = IEHelper.GetDirectUI(ieWindow);
                if (directUIWD != null) {
                    ieAccessible = new Accessible(directUIWD.Handle);
                }
                if (ieAccessible == null) {
                    LOG.InfoFormat("Active Window is {0}", activeWindow.Text);
                    if (!ieWindow.Equals(activeWindow)) {
                        LOG.WarnFormat("No ieAccessible for {0}", ieWindow.Text);
                        continue;
                    }
                    LOG.DebugFormat("No ieAccessible, but the active window is an IE window: {0}, ", ieWindow.Text);
                }

                try {
                    // Get the Document
                    IHTMLDocument2 document2 = null;
                    uint windowMessage = User32.RegisterWindowMessage("WM_HTML_GETOBJECT");
                    if (windowMessage == 0) {
                        LOG.WarnFormat("Couldn't register WM_HTML_GETOBJECT");
                        continue;
                    }

                    WindowDetails ieServer= ieWindow.GetChild("Internet Explorer_Server");
                    if (ieServer == null) {
                        LOG.WarnFormat("No Internet Explorer_Server for {0}", ieWindow.Text);
                        continue;
                    }
                    LOG.DebugFormat("Trying WM_HTML_GETOBJECT on {0}", ieServer.ClassName);
                    UIntPtr response;
                    User32.SendMessageTimeout(ieServer.Handle, windowMessage, IntPtr.Zero, IntPtr.Zero, SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out response);
                    if (response != UIntPtr.Zero) {
                        document2 = (IHTMLDocument2)Accessible.ObjectFromLresult(response, typeof(IHTMLDocument).GUID, IntPtr.Zero);
                        if (document2 == null) {
                            LOG.Error("No IHTMLDocument2 found");
                            continue;
                        }
                    } else {
                        LOG.Error("No answer on WM_HTML_GETOBJECT.");
                        continue;
                    }

                    // Get the content window handle for the shellWindow.Document
                    IOleWindow oleWindow = (IOleWindow)document2;
                    IntPtr contentWindowHandle = IntPtr.Zero;
                    if (oleWindow != null) {
                        oleWindow.GetWindow(out contentWindowHandle);
                    }

                    if (contentWindowHandle != IntPtr.Zero) {
                        // Get the HTMLDocument to check the hasFocus
                        // See: http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/60c6c95d-377c-4bf4-860d-390840fce31c/
                        IHTMLDocument4 document4 = (IHTMLDocument4)document2;

                        if (document4.hasFocus()) {
                            LOG.DebugFormat("Matched focused document: {0}", document2.title);
                            // Look no further, we got what we wanted!
                            returnDocument2 = document2;
                            returnWindow = new WindowDetails(contentWindowHandle);
                            break;
                        }
                        try {
                            if (ieWindow.Equals(activeWindow)) {
                                returnDocument2 = document2;
                                returnWindow = new WindowDetails(contentWindowHandle);
                                break;
                            } else if (ieAccessible != null && returnWindow == null && document2.title.Equals(ieAccessible.IEActiveTabCaption) ) {
                                LOG.DebugFormat("Title: {0}", document2.title);
                                returnDocument2 = document2;
                                returnWindow = new WindowDetails(contentWindowHandle);
                            } else {
                                alternativeReturnDocument2 = document2;
                                alternativeReturnWindow = new WindowDetails(contentWindowHandle);
                            }
                        } catch (Exception) {
                            alternativeReturnDocument2 = document2;
                            alternativeReturnWindow = new WindowDetails(contentWindowHandle);
                        }
                    }
                } catch (Exception e) {
                    LOG.Error(e);
                    LOG.DebugFormat("Major problem: Problem retrieving Document from {0}", ieWindow.Text);
                }
            }

            // check if we have something to return
            if (returnWindow != null) {
                // As it doesn't have focus, make sure it's active
                returnWindow.Restore();
                returnWindow.GetParent();

                // Create the container
                returnDocumentContainer = new DocumentContainer(returnDocument2, returnWindow);
            }

            if (returnDocumentContainer == null && alternativeReturnDocument2 != null) {
                // As it doesn't have focus, make sure it's active
                alternativeReturnWindow.Restore();
                alternativeReturnWindow.GetParent();
                // Create the container
                returnDocumentContainer =  new DocumentContainer(alternativeReturnDocument2, alternativeReturnWindow);
            }
            return returnDocumentContainer;
        }
예제 #42
0
        /// <summary>
        /// Private helper method for the constructors
        /// </summary>
        /// <param name="document2">IHTMLDocument2</param>
        /// <param name="contentWindow">WindowDetails</param>
        private void Init(IHTMLDocument2 document2, WindowDetails contentWindow)
        {
            this.document2 = document2;
            this.contentWindow = contentWindow;
            this.document3 = document2 as IHTMLDocument3;
            // Check what access method is needed for the document
            IHTMLDocument5 document5 = (IHTMLDocument5)document2;
            //compatibility mode affects how height is computed
            if ((document3.documentElement != null) && (!document5.compatMode.Equals("BackCompat"))) {
                isDTD = true;
            } else {
                isDTD = false;
            }
            Rectangle clientRectangle = contentWindow.WindowRectangle;
            try {
                IHTMLWindow3 window3 = (IHTMLWindow3)document2.parentWindow;
                IHTMLWindow2 window2 = (IHTMLWindow2)document2.parentWindow;
                IHTMLScreen2 screen2 = (IHTMLScreen2)window2.screen;
                IHTMLScreen screen = window2.screen;
                if (parent != null) {
                    // Copy parent values
                    zoomLevelX = parent.zoomLevelX;
                    zoomLevelY = parent.zoomLevelY;
                    viewportRectangle = parent.viewportRectangle;
                } else {
                    //DisableScrollbars(document2);

                    // Calculate zoom level
                    zoomLevelX = (double)screen2.deviceXDPI/(double)screen2.logicalXDPI;
                    zoomLevelY = (double)screen2.deviceYDPI/(double)screen2.logicalYDPI;

                    // Calculate the viewport rectangle, needed if there is a frame around the html window
                    LOG.DebugFormat("Screen {0}x{1}", ScaleX(screen.width), ScaleY(screen.height));
                    LOG.DebugFormat("Screen location {0},{1}", window3.screenLeft, window3.screenTop);
                    LOG.DebugFormat("Window rectangle {0}", clientRectangle);
                    LOG.DebugFormat("Client size {0}x{1}", ClientWidth, ClientHeight);
                    int diffX = clientRectangle.Width - ClientWidth;
                    int diffY = clientRectangle.Height - ClientHeight;
                    // If there is a border around the inner window, the diff == 4
                    // If there is a border AND a scrollbar the diff == 20
                    if ((diffX == 4 || diffX >= 20) && (diffY == 4 || diffY >= 20)) {
                        Point viewportOffset = new Point(2, 2);
                        Size viewportSize = new Size(ClientWidth, ClientHeight);
                        viewportRectangle = new Rectangle(viewportOffset, viewportSize);
                        LOG.DebugFormat("viewportRect {0}", viewportRectangle);
                    }
                }
                LOG.DebugFormat("Zoomlevel {0}, {1}", zoomLevelX, zoomLevelY);

            } catch (Exception e) {
                LOG.Warn("Can't get certain properties for documents, using default.  due to: ", e);

            }

            LOG.DebugFormat("Calculated location {0} for {1}", startLocation, document2.title);
            sourceLocation = new Point(ScaleX((int)startLocation.X), ScaleY((int)startLocation.Y));
            destinationLocation = new Point(ScaleX((int)startLocation.X), ScaleY((int)startLocation.Y));

            try {
                if (name == null) {
                    name = document2.title;
                }
            } catch {
            }
            try {
                url = document2.url;
            } catch {
            }

            if (parent != null) {
                return;
            }
            IHTMLFramesCollection2 frameCollection = (IHTMLFramesCollection2)document2.frames;
            for(int frame = 0; frame < frameCollection.length; frame++) {
                IHTMLWindow2 frameWindow = frameCollection.item(frame);
                try {
                    DocumentContainer frameData = new DocumentContainer(frameWindow, contentWindow, this);
                    // check if frame is hidden
                    if (!frameData.isHidden) {
                        LOG.DebugFormat("Creating DocumentContainer for Frame {0} found in window with rectangle {1}", frameData.name, frameData.SourceRectangle);
                        frames.Add(frameData);
                    } else {
                        LOG.DebugFormat("Skipping frame {0}", frameData.Name);
                    }
                } catch (Exception e) {
                    LOG.Warn("Problem while trying to get information from a frame, skipping the frame!", e);
                }
            }
            // Correct iframe locations
            foreach (IHTMLElement frameElement in document3.getElementsByTagName("IFRAME")){
                try {
                    CorrectFrameLocations(frameElement);
                } catch (Exception e) {
                    LOG.Warn("Problem while trying to get information from an iframe, skipping the frame!", e);
                }
            }
        }
예제 #43
0
 public DocumentContainer(IHTMLDocument2 document2, WindowDetails contentWindow)
 {
     Init(document2, contentWindow);
     LOG.DebugFormat("Creating DocumentContainer for Document {0} found in window with rectangle {1}", name, SourceRectangle);
 }
예제 #44
0
        public ImageEditorForm(ISurface iSurface, bool outputMade)
        {
            EditorList.Add(this);

            InitializeComponent();

            if (EditorConfiguration.MatchSizeToCapture)
            {
                RECT lastPosition = EditorConfiguration.GetEditorPlacement().NormalPosition;
                this.StartPosition = FormStartPosition.Manual;
                this.Location = new Point(lastPosition.Left, lastPosition.Top);
            }
            else
            {
                Load += delegate
                {
                    //Make sure the editor is placed on the same location as the last editor was on close
                    WindowDetails thisForm = new WindowDetails(Handle)
                    {
                        WindowPlacement = EditorConfiguration.GetEditorPlacement()
                    };
                };
            }

            // init surface
            Surface = iSurface;
            // Intial "saved" flag for asking if the image needs to be save
            _surface.Modified = !outputMade;

            UpdateUi();

            // Workaround: As the cursor is (mostly) selected on the surface a funny artifact is visible, this fixes it.
            //HideToolstripItems();
        }
예제 #45
0
        private void CaptureWithFeedback()
        {
            // The following, to be precise the HideApp, causes the app to close as described in BUG-1620
            // Added check for metro (Modern UI) apps, which might be maximized and cover the screen.

            //foreach(WindowDetails app in WindowDetails.GetMetroApps()) {
            //	if (app.Maximised) {
            //		app.HideApp();
            //	}
            //}

            using (CaptureForm captureForm = new CaptureForm(_capture, _windows)) {
                DialogResult result = captureForm.ShowDialog();
                if (result == DialogResult.OK) {
                    _selectedCaptureWindow = captureForm.SelectedCaptureWindow;
                    _captureRect = captureForm.CaptureRectangle;
                    // Get title
                    if (_selectedCaptureWindow != null) {
                        _capture.CaptureDetails.Title = _selectedCaptureWindow.Text;
                    }

                    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
                        // Important here is that the location needs to be offsetted back to screen coordinates!
                        Rectangle tmpRectangle = _captureRect;
                        tmpRectangle.Offset(_capture.ScreenBounds.Location.X, _capture.ScreenBounds.Location.Y);
                        conf.LastCapturedRegion = tmpRectangle;
                        HandleCapture();
                    }
                }
            }
        }
예제 #46
0
 public static void CaptureWindow(WindowDetails windowToCapture)
 {
     using (CaptureHelper captureHelper = new CaptureHelper(CaptureMode.ActiveWindow)) {
         captureHelper.SelectedCaptureWindow = windowToCapture;
         captureHelper.MakeCapture();
     }
 }
예제 #47
0
 void CaptureFormKeyDown(object sender, KeyEventArgs e)
 {
     // Check fixmode
     if (e.KeyCode == Keys.ShiftKey) {
         if (fixMode == FixMode.None) {
             fixMode = FixMode.Initiated;
             return;
         }
     }
     if (e.KeyCode == Keys.Escape) {
         DialogResult = DialogResult.Cancel;
     } else if (e.KeyCode == Keys.M) {
         // Toggle mouse cursor
         capture.CursorVisible = !capture.CursorVisible;
         pictureBox.Invalidate();
     } else if (e.KeyCode == Keys.V && conf.isExperimentalFeatureEnabled("Video")) {
         capture.CaptureDetails.CaptureMode = CaptureMode.Video;
         pictureBox.Invalidate();
     } else if (e.KeyCode == Keys.Space) {
         switch (captureMode) {
             case CaptureMode.Region:
                 captureMode = CaptureMode.Window;
                 break;
             case CaptureMode.Window:
                 captureMode = CaptureMode.Region;
                 break;
         }
         pictureBox.Invalidate();
         selectedCaptureWindow = null;
         PictureBoxMouseMove(this, new MouseEventArgs(MouseButtons.None, 0, Cursor.Position.X, Cursor.Position.Y, 0));
     } else if (e.KeyCode == Keys.Return && captureMode == CaptureMode.Window) {
         DialogResult = DialogResult.OK;
     }
 }
예제 #48
0
		/// <summary>
		/// Handle the key down event
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		void CaptureFormKeyDown(object sender, KeyEventArgs e) {
			int step = _isCtrlPressed ? 10 : 1;

			switch (e.KeyCode) {
				case Keys.Up:
					Cursor.Position = new Point(Cursor.Position.X, Cursor.Position.Y - step);
					break;
				case Keys.Down:
					Cursor.Position = new Point(Cursor.Position.X, Cursor.Position.Y + step);
					break;
				case Keys.Left:
					Cursor.Position = new Point(Cursor.Position.X - step, Cursor.Position.Y);
					break;
				case Keys.Right:
					Cursor.Position = new Point(Cursor.Position.X + step, Cursor.Position.Y);
					break;
				case Keys.ShiftKey:
					// Fixmode
					if (_fixMode == FixMode.None) {
						_fixMode = FixMode.Initiated;
					}
					break;
				case Keys.ControlKey:
					_isCtrlPressed = true;
					break;
				case Keys.Escape:
					// Cancel
					DialogResult = DialogResult.Cancel;
					break;
				case Keys.M:
					// Toggle mouse cursor
					_capture.CursorVisible = !_capture.CursorVisible;
					Invalidate();
					break;
				//// TODO: Enable when the screen capture code works reliable
				//case Keys.V:
				//	// Video
				//	if (capture.CaptureDetails.CaptureMode != CaptureMode.Video) {
				//		capture.CaptureDetails.CaptureMode = CaptureMode.Video;
				//	} else {
				//		capture.CaptureDetails.CaptureMode = captureMode;
				//	}
				//	Invalidate();
				//	break;
				case Keys.Z:
					if (_captureMode == CaptureMode.Region) {
						// Toggle zoom
						Conf.ZoomerEnabled = !Conf.ZoomerEnabled;
						InitializeZoomer(Conf.ZoomerEnabled);
						Invalidate();
					}
					break;
				case Keys.Space:
					// Toggle capture mode
					switch (_captureMode) {
						case CaptureMode.Region:
							// Set the window capture mode
							_captureMode = CaptureMode.Window;
							// "Fade out" Zoom
							InitializeZoomer(false);
							// "Fade in" window
							_windowAnimator = new RectangleAnimator(new Rectangle(_cursorPos, Size.Empty), _captureRect, FramesForMillis(700), EasingType.Quintic, EasingMode.EaseOut);
							_captureRect = Rectangle.Empty;
							Invalidate();
							break;
						case CaptureMode.Window:
							// Set the region capture mode
							_captureMode = CaptureMode.Region;
							// "Fade out" window
							_windowAnimator.ChangeDestination(new Rectangle(_cursorPos, Size.Empty), FramesForMillis(700));
							// Fade in zoom
							InitializeZoomer(Conf.ZoomerEnabled);
							_captureRect = Rectangle.Empty;
							Invalidate();
							break;
					}
					_selectedCaptureWindow = null;
					OnMouseMove(this, new MouseEventArgs(MouseButtons.None, 0, Cursor.Position.X, Cursor.Position.Y, 0));
					break;
				case Keys.Return:
					// Confirm
					if (_captureMode == CaptureMode.Window) {
						DialogResult = DialogResult.OK;
					} else if (!_mouseDown) {
						HandleMouseDown();
					} else if (_mouseDown) {
						HandleMouseUp();
					}
					break;
			}
		}
예제 #49
0
		/// <summary>
		/// update the frame, this only invalidates
		/// </summary>
		protected override void Animate() {
			Point lastPos = _cursorPos;
			_cursorPos = _mouseMovePos;

			if (_selectedCaptureWindow != null && lastPos.Equals(_cursorPos) && !isAnimating(_zoomAnimator) && !isAnimating(_windowAnimator)) {
				return;
			}

			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;
			lock (_windows) {
				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)) {
				_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.WindowRectangle;
					// As the ClientRectangle is not in Bitmap coordinates, we need to correct.
					_captureRect.Offset(-_capture.ScreenBounds.Location.X, -_capture.ScreenBounds.Location.Y);
				}
			}

			Rectangle invalidateRectangle;
			if (_mouseDown && (_captureMode != CaptureMode.Window)) {
				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(CultureInfo.InvariantCulture), rulerFont);
					x1 -= measureWidth.Width + 15;

					Size measureHeight = TextRenderer.MeasureText(textForHeight.ToString(CultureInfo.InvariantCulture), rulerFont);
					y1 -= measureHeight.Height + 10;
				}
				invalidateRectangle = new Rectangle(x1,y1, x2-x1, y2-y1);
				Invalidate(invalidateRectangle);
			} else if (_captureMode != CaptureMode.Window) {
				if (!isTerminalServerSession) {
					Rectangle allScreenBounds = WindowCapture.GetScreenBounds();
					allScreenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(allScreenBounds.Location);
					if (verticalMove) {
						// Before
						invalidateRectangle = GuiRectangle.GetGuiRectangle(allScreenBounds.Left, lastPos.Y - 2, Width + 2, 45);
						Invalidate(invalidateRectangle);
						// After
						invalidateRectangle = GuiRectangle.GetGuiRectangle(allScreenBounds.Left, _cursorPos.Y - 2, Width + 2, 45);
						Invalidate(invalidateRectangle);
					}
					if (horizontalMove) {
						// Before
						invalidateRectangle = GuiRectangle.GetGuiRectangle(lastPos.X - 2, allScreenBounds.Top, 75, Height + 2);
						Invalidate(invalidateRectangle);
						// After
						invalidateRectangle = GuiRectangle.GetGuiRectangle(_cursorPos.X - 2, allScreenBounds.Top, 75, Height + 2);
						Invalidate(invalidateRectangle);
					}
				}
			} else {
				if (_selectedCaptureWindow != null && !_selectedCaptureWindow.Equals(lastWindow)) {
					// Window changes, make new animation from current to target
					_windowAnimator.ChangeDestination(_captureRect, FramesForMillis(700));
				}
			}
			// always animate the Window area through to the last frame, so we see the fade-in/out untill the end
			// Using a safety "offset" to make sure the text is invalidated too
			const int safetySize = 30;
			// Check if the 
			if (isAnimating(_windowAnimator)) {
				invalidateRectangle = _windowAnimator.Current;
				invalidateRectangle.Inflate(safetySize, safetySize);
				Invalidate(invalidateRectangle);
				invalidateRectangle = _windowAnimator.Next();
				invalidateRectangle.Inflate(safetySize, safetySize);
				Invalidate(invalidateRectangle);
				// Check if this was the last of the windows animations in the normal region capture.
				if (_captureMode != CaptureMode.Window && !isAnimating(_windowAnimator)) {
					Invalidate();
				}
			}

			if (_zoomAnimator != null && (isAnimating(_zoomAnimator) || _captureMode != CaptureMode.Window)) {
				// Make sure we invalidate the old zoom area
				invalidateRectangle = _zoomAnimator.Current;
				invalidateRectangle.Offset(lastPos);
				Invalidate(invalidateRectangle);
				// Only verify if we are really showing the zoom, not the outgoing animation
				if (Conf.ZoomerEnabled && _captureMode != CaptureMode.Window) {
					VerifyZoomAnimation(_cursorPos, false);
				}
				// The following logic is not needed, next always returns the current if there are no frames left
				// but it makes more sense if we want to change something in the logic
				if (isAnimating(_zoomAnimator)) {
					invalidateRectangle = _zoomAnimator.Next();
				} else {
					invalidateRectangle = _zoomAnimator.Current;
				}
				invalidateRectangle.Offset(_cursorPos);
				Invalidate(invalidateRectangle);
			}
			// Force update "now"
			Update();
		}
예제 #50
0
 public ScreenCaptureHelper(WindowDetails recordingWindow)
 {
     this.recordingWindow = recordingWindow;
 }
예제 #51
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;
        }
예제 #52
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();
            }
        }
        /// <summary>
        /// This method takes the actual capture of the document (frame)
        /// </summary>
        /// <param name="frameDocument"></param>
        /// <param name="contentWindowDetails">Needed for referencing the location of the frame</param>
        /// <returns>Bitmap with the capture</returns>
        private static void drawDocument(DocumentContainer documentContainer, WindowDetails contentWindowDetails, Graphics graphicsTarget)
        {
            documentContainer.setAttribute("scroll", 1);

            //Get Browser Window Width & Height
            int pageWidth = documentContainer.ScrollWidth;
            int pageHeight = documentContainer.ScrollHeight;
            if (pageWidth * pageHeight == 0) {
                LOG.WarnFormat("Empty page for DocumentContainer {0}: {1}", documentContainer.Name, documentContainer.Url);
                return;
            }

            //Get Screen Width & Height (this is better as the WindowDetails.ClientRectangle as the real visible parts are there!
            int viewportWidth = documentContainer.ClientWidth;
            int viewportHeight = documentContainer.ClientHeight;
            if (viewportWidth * viewportHeight == 0) {
                LOG.WarnFormat("Empty viewport for DocumentContainer {0}: {1}", documentContainer.Name, documentContainer.Url);
                return;
            }

            // Store the current location so we can set the browser back and use it for the mouse cursor
            int startLeft = documentContainer.ScrollLeft;
            int startTop = documentContainer.ScrollTop;

            LOG.DebugFormat("Capturing {4} with total size {0},{1} displayed with size {2},{3}", pageWidth, pageHeight, viewportWidth, viewportHeight, documentContainer.Name);

            // Variable used for looping horizontally
            int horizontalPage = 0;

            // The location of the browser, used as the destination into the bitmap target
            Point targetOffset = new Point();

            // Loop of the pages and make a copy of the visible viewport
            while ((horizontalPage * viewportWidth) < pageWidth) {
                // Scroll to location
                documentContainer.ScrollLeft = viewportWidth * horizontalPage;
                targetOffset.X = documentContainer.ScrollLeft;

                // Variable used for looping vertically
                int verticalPage = 0;
                while ((verticalPage * viewportHeight) < pageHeight) {
                    // Scroll to location
                    documentContainer.ScrollTop = viewportHeight * verticalPage;
                    //Shoot visible window
                    targetOffset.Y  = documentContainer.ScrollTop;

                    // Draw the captured fragment to the target, but "crop" the scrollbars etc while capturing
                    Size viewPortSize = new Size(viewportWidth, viewportHeight);
                    Rectangle clientRectangle = new Rectangle(documentContainer.SourceLocation, viewPortSize);
                    Image fragment = contentWindowDetails.PrintWindow();
                    if (fragment != null) {
                        LOG.DebugFormat("Captured fragment size: {0}x{1}", fragment.Width, fragment.Height);
                        try {
                            // cut all junk, due to IE "border" we need to remove some parts
                            Rectangle viewportRect = documentContainer.ViewportRectangle;
                            if (!viewportRect.IsEmpty) {
                                LOG.DebugFormat("Cropping to viewport: {0}", viewportRect);
                                ImageHelper.Crop(ref fragment, ref viewportRect);
                            }
                            LOG.DebugFormat("Cropping to clientRectangle: {0}", clientRectangle);
                            // Crop to clientRectangle
                            if (ImageHelper.Crop(ref fragment, ref clientRectangle)) {
                                Point targetLocation = new Point(documentContainer.DestinationLocation.X, documentContainer.DestinationLocation.Y);
                                LOG.DebugFormat("Fragment targetLocation is {0}", targetLocation);
                                targetLocation.Offset(targetOffset);
                                LOG.DebugFormat("After offsetting the fragment targetLocation is {0}", targetLocation);
                                LOG.DebugFormat("Drawing fragment of size {0} to {1}", fragment.Size, targetLocation);
                                graphicsTarget.DrawImage(fragment, targetLocation);
                                graphicsTarget.Flush();
                            } else {
                                // somehow we are capturing nothing!?
                                LOG.WarnFormat("Crop of {0} failed?", documentContainer.Name);
                                break;
                            }
                        } finally {
                            fragment.Dispose();
                        }
                    } else {
                        LOG.WarnFormat("Capture of {0} failed!", documentContainer.Name);
                    }
                    verticalPage++;
                }
                horizontalPage++;
            }
            // Return to where we were
            documentContainer.ScrollLeft = startLeft;
            documentContainer.ScrollTop = startTop;
        }
예제 #54
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 = 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;
            lock (windows) {
                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)) {
                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.WindowRectangle;
                    // 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);
                    }
                } else {
                    if (!conf.OptimizeForRDP) {
                        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);
                        }
                    }
                }
            }
        }
예제 #55
0
        public ImageEditorForm(ISurface iSurface, bool outputMade)
        {
            EditorList.Add(this);

            InitializeComponent();

            if (EditorConfiguration.MatchSizeToCapture)
            {
                RECT lastPosition = EditorConfiguration.GetEditorPlacement().NormalPosition;

                WindowPlacement wp = new WindowDetails(Handle).WindowPlacement;
                wp.NormalPosition.Top = lastPosition.Top;
                wp.NormalPosition.Left = lastPosition.Left;
                // don't actually show window now (it is done later)
                wp.ShowCmd = ShowWindowCommand.Hide;

                this.StartPosition = FormStartPosition.Manual;

                WindowDetails thisForm = new WindowDetails(Handle)
                {
                    WindowPlacement = wp
                };

                // Once image is loaded into window, size and position window
                Load += delegate
                {
                    Rectangle workingArea = Screen.FromControl(this).WorkingArea;
                    WindowPlacement windowPlacement = new WindowDetails(Handle).WindowPlacement;

                    if (EditorConfiguration.MaximizeWhenLargeImage)
                    {
                        if ((windowPlacement.NormalPosition.Width > workingArea.Width) || (windowPlacement.NormalPosition.Height > workingArea.Height))
                        {
                            windowPlacement.ShowCmd = ShowWindowCommand.Maximize;
                        }
                    }

                    if (windowPlacement.NormalPosition.Right > workingArea.Right)
                    {
                        int toMoveLeft = windowPlacement.NormalPosition.Right - workingArea.Right;
                        if (windowPlacement.NormalPosition.Left - toMoveLeft < 0)
                            toMoveLeft = windowPlacement.NormalPosition.Left;

                        windowPlacement.NormalPosition.Left -= toMoveLeft;
                        windowPlacement.NormalPosition.Right -= toMoveLeft;
                    }
                    if (windowPlacement.NormalPosition.Bottom > workingArea.Bottom)
                    {
                        int toMoveUp = windowPlacement.NormalPosition.Bottom - workingArea.Bottom;
                        if (windowPlacement.NormalPosition.Top - toMoveUp < 0)
                            toMoveUp = windowPlacement.NormalPosition.Top;

                        windowPlacement.NormalPosition.Top -= toMoveUp;
                        windowPlacement.NormalPosition.Bottom -= toMoveUp;
                    }
                    WindowDetails thisForm1 = new WindowDetails(Handle) { WindowPlacement = windowPlacement };
                };
            }
            else
            {
                Load += delegate
                {
                    //Make sure the editor is placed on the same location as the last editor was on close
                    WindowDetails thisForm = new WindowDetails(Handle)
                    {
                        WindowPlacement = EditorConfiguration.GetEditorPlacement()
                    };
                };
            }

            // init surface
            Surface = iSurface;
            // Intial "saved" flag for asking if the image needs to be save
            _surface.Modified = !outputMade;

            UpdateUi();

            // Workaround: As the cursor is (mostly) selected on the surface a funny artifact is visible, this fixes it.
            //HideToolstripItems();
        }
예제 #56
0
 public static void CaptureIE(bool captureMouse, WindowDetails windowToCapture)
 {
     using (CaptureHelper captureHelper = new CaptureHelper(CaptureMode.IE, captureMouse)) {
         captureHelper.SelectedCaptureWindow = windowToCapture;
         captureHelper.MakeCapture();
     }
 }
예제 #57
0
 /// <summary>
 /// Select the window to capture, this has logic which takes care of certain special applications
 /// like TOAD or Excel
 /// </summary>
 /// <param name="windowToCapture">WindowDetails with the target Window</param>
 /// <returns>WindowDetails with the target Window OR a replacement</returns>
 public static WindowDetails SelectCaptureWindow(WindowDetails windowToCapture)
 {
     Rectangle windowRectangle = windowToCapture.WindowRectangle;
     if (windowRectangle.Width == 0 || windowRectangle.Height == 0) {
         LOG.WarnFormat("Window {0} has nothing to capture, using workaround to find other window of same process.", windowToCapture.Text);
         // Trying workaround, the size 0 arrises with e.g. Toad.exe, has a different Window when minimized
         WindowDetails linkedWindow = WindowDetails.GetLinkedWindow(windowToCapture);
         if (linkedWindow != null) {
             windowRectangle = linkedWindow.WindowRectangle;
             windowToCapture = linkedWindow;
         } else {
             return null;
         }
     }
     return windowToCapture;
 }
예제 #58
0
 void CaptureFormKeyDown(object sender, KeyEventArgs e)
 {
     if (MouseHelper.CheckKeyDownForFixing(e.KeyCode))
      {
     return;
      }
      if (e.KeyCode == Keys.Escape)
      {
     StopCapturing(true);
      }
      else if (e.KeyCode == Keys.M)
      {
     // Toggle mouse cursor
     capture.CursorVisible = !capture.CursorVisible;
     pictureBox.Invalidate();
      }
      else if (e.KeyCode == Keys.V)
      {
     capture.CaptureDetails.CaptureMode = CaptureMode.Video;
     pictureBox.Invalidate();
      }
      else if (e.KeyCode == Keys.Space)
      {
     switch (captureMode)
     {
        case CaptureMode.Region:
           captureMode = CaptureMode.Window;
           break;
        case CaptureMode.Window:
           captureMode = CaptureMode.Region;
           break;
     }
     pictureBox.Invalidate();
     selectedCaptureWindow = null;
     PictureBoxMouseMove(this, new MouseEventArgs(MouseButtons.None, 0, Cursor.Position.X, Cursor.Position.Y, 0));
      }
      else if (e.KeyCode == Keys.Return && captureMode == CaptureMode.Window)
      {
     finishCaptureWithFeedback();
      }
 }
예제 #59
0
 private bool CaptureActiveWindow()
 {
     bool presupplied = false;
     LOG.Debug("CaptureActiveWindow");
     if (_selectedCaptureWindow != null) {
         LOG.Debug("Using supplied window");
         presupplied = true;
     } else {
         _selectedCaptureWindow = WindowDetails.GetActiveWindow();
         if (_selectedCaptureWindow != null) {
             LOG.DebugFormat("Capturing window: {0} with {1}", _selectedCaptureWindow.Text, _selectedCaptureWindow.WindowRectangle);
         }
     }
     if (_selectedCaptureWindow == null || (!presupplied && _selectedCaptureWindow.Iconic)) {
         LOG.Warn("No window to capture!");
         // Nothing to capture, code up in the stack will capture the full screen
         return false;
     }
     if (!presupplied && _selectedCaptureWindow != null && _selectedCaptureWindow.Iconic) {
         // Restore the window making sure it's visible!
         // This is done mainly for a screen capture, but some applications like Excel and TOAD have weird behaviour!
         _selectedCaptureWindow.Restore();
     }
     _selectedCaptureWindow = SelectCaptureWindow(_selectedCaptureWindow);
     if (_selectedCaptureWindow == null) {
         LOG.Warn("No window to capture, after SelectCaptureWindow!");
         // Nothing to capture, code up in the stack will capture the full screen
         return false;
     }
     // Fix for Bug #3430560
     conf.LastCapturedRegion = _selectedCaptureWindow.WindowRectangle;
     bool returnValue = CaptureWindow(_selectedCaptureWindow, _capture, conf.WindowCaptureMode) != null;
     return returnValue;
 }
예제 #60
0
 /// <summary>
 /// Make capture of window
 /// </summary>
 /// <param name="window">WindowDetails of the window to capture</param>
 /// <param name="captureMouseCursor">bool false if the mouse should not be captured, true if the configuration should be checked</param>
 public void MakeCapture(WindowDetails window, CaptureHandler captureHandler)
 {
     Capture passingCapture = new Capture();
      passingCapture.CaptureDetails.CaptureHandler = captureHandler;
      selectedCaptureWindow = window;
      MakeCapture(CaptureMode.ActiveWindow, false, passingCapture);
 }