/// <summary>
        /// Place the clip back onto the clipboard
        /// </summary>
        /// <param name="clip">Clip</param>
        /// <param name="fromExisting">bool</param>
        public static void PlaceOnClipboard(this Clip clip, bool fromExisting = false)
        {
            var handle = WinProcHandler.Instance.Handle;

            if (InteropWindowFactory.CreateFor(clip.OriginalWindowHandle).Exists())
            {
                handle = clip.OriginalWindowHandle;
            }
            // TODO: Prevent detecting the restore, especially if Dopy doesn't "paste" with it's Window handle
            using var clipboardAccessToken = ClipboardNative.Access(handle);
            clipboardAccessToken.ClearContents();
            // Make the clipboard as modified by DOPY
            if (fromExisting || clip.IsModifiedByDopy)
            {
                clipboardAccessToken.SetAsUnicodeString($"On {DateTime.Now:O}", ClipboardFormats.Dopy);
            }
            foreach (var key in clip.Contents.Keys)
            {
                clipboardAccessToken.SetAsStream(key, clip.Contents[key]);
            }
            if (!string.IsNullOrEmpty(clip.ClipboardText))
            {
                clipboardAccessToken.SetAsUnicodeString(clip.ClipboardText);
            }
        }
Exemple #2
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 (var excelApplication = GetExcelApplication())
     {
         if (excelApplication == null)
         {
             return;
         }
         using (var workbooks = excelApplication.Workbooks)
         {
             for (var i = 1; i <= workbooks.Count; i++)
             {
                 using (var workbook = workbooks[i])
                 {
                     if (workbook != null && workbook.Name.StartsWith(workbookName))
                     {
                         InsertIntoExistingWorkbook(workbook, tmpFile, imageSize);
                     }
                 }
             }
         }
         var hWnd = excelApplication.Hwnd;
         if (hWnd > 0)
         {
             // TODO: Await
             InteropWindowFactory.CreateFor(new IntPtr(hWnd)).ToForegroundAsync();
         }
     }
 }
Exemple #3
0
 /// <summary>
 ///     Make sure the form is visible, if this is wanted
 /// </summary>
 /// <param name="e">EventArgs</param>
 protected override async void OnShown(EventArgs e)
 {
     base.OnShown(e);
     if (ToFront)
     {
         await InteropWindowFactory.CreateFor(Handle).ToForegroundAsync();
     }
 }
        public void Fill()
        {
            var interopWindow = InteropWindowFactory.CreateFor(_notepadProcess.MainWindowHandle);

            if (interopWindow.Handle == IntPtr.Zero)
            {
                throw new NotSupportedException("Somehow the window was not found!");
            }
            interopWindow.Fill();
        }
Exemple #5
0
        public Window GetWindow(IntPtr handle)
        {
            var interopWindow = InteropWindowFactory.CreateFor(handle);

            interopWindow.Fill(InteropWindowCacheFlags.Info | InteropWindowCacheFlags.Text);
            var windowInfo = interopWindow.Info.Value;

            Dwm.GetExtendedFrameBounds(handle, out var nativeBounds);
            var innerBounds = (Rectangle)nativeBounds;
            var outerBounds = (Rectangle)windowInfo.Bounds;

            Rectangle bounds;
            Thickness border;

            if (outerBounds.Width > 0 || outerBounds.Height > 0)
            {
                var rawBorder = innerBounds.GetBorder(outerBounds);
                if (rawBorder.Left < 0 || rawBorder.Top < 0 || rawBorder.Right < 0 || rawBorder.Right < 0)
                {
                    bounds = new Rectangle(
                        innerBounds.Left - Math.Min(rawBorder.Left, 0),
                        innerBounds.Top - Math.Min(rawBorder.Top, 0),
                        innerBounds.Width - Math.Min(rawBorder.Left, 0) - Math.Min(rawBorder.Right, 0),
                        innerBounds.Height - Math.Min(rawBorder.Top, 0) - Math.Min(rawBorder.Bottom, 0));
                    border = new Thickness(
                        Math.Max(rawBorder.Left, 0),
                        Math.Max(rawBorder.Top, 0),
                        Math.Max(rawBorder.Right, 0),
                        Math.Max(rawBorder.Bottom, 0));
                }
                else
                {
                    bounds = innerBounds;
                    border = rawBorder;
                }
            }
            else
            {
                bounds = innerBounds;
                border = Thickness.Empty;
            }

            var dpi = (int)NativeDpiMethods.GetDpiForWindow(handle);

            return(new Window
            {
                Handle = handle,
                Title = interopWindow.Text,
                Bounds = bounds,
                Border = border,
                Dpi = new Point(dpi, dpi),
            });
        }
        //[Fact]
        public void Test_GetInfo_WithParentCrop()
        {
            const int testHandle = 0x000806a6;
            var       testWindow = InteropWindowFactory.CreateFor(testHandle);
            var       ws         = testWindow.GetWindowScroller();
            var       info1      = ws.ScrollingWindow.GetInfo();

            Assert.True(info1.Bounds.Width < 1920);
            var info2 = testWindow.GetInfo();

            Assert.True(info2.Bounds.Width < 1920);
        }
        /// <summary>
        ///     Get the icon for a hWnd
        /// </summary>
        /// <typeparam name="TIcon">The return type for the icon, can be Icon, Bitmap or BitmapSource</typeparam>
        /// <param name="window">IInteropWindow</param>
        /// <param name="useLargeIcons">true to try to get a big icon first</param>
        /// <returns>TIcon</returns>
        public static TIcon GetIcon <TIcon>(this IInteropWindow window, bool useLargeIcons = false) where TIcon : class
        {
            if (window.IsApp())
            {
                return(IconHelper.GetAppLogo <TIcon>(window));
            }
            var icon = GetIconFromWindow <TIcon>(window, useLargeIcons);

            if (icon != null)
            {
                return(icon);
            }
            var processId = window.GetProcessId();
            // Try to get the icon from the process file itself, if we can query the path
            var processPath = Kernel32Api.GetProcessPath(processId);

            if (processPath != null)
            {
                return(IconHelper.ExtractAssociatedIcon <TIcon>(processPath, useLargeIcon: useLargeIcons));
            }
            // Look at the windows of the other similar named processes
            using (var process = Process.GetProcessById(processId))
            {
                var processName = process.ProcessName;
                foreach (var possibleParentProcess in Process.GetProcessesByName(processName))
                {
                    var parentProcessWindow = InteropWindowFactory.CreateFor(possibleParentProcess.MainWindowHandle);
                    icon = GetIconFromWindow <TIcon>(parentProcessWindow, useLargeIcons);
                    if (icon != null)
                    {
                        return(icon);
                    }
                    possibleParentProcess.Dispose();
                }
            }
            // Try to find another window, which belongs to the same process, and get the icon from there
            foreach (var otherWindow in InteropWindowQuery.GetTopWindows().Where(interopWindow => interopWindow.GetProcessId() == processId))
            {
                if (otherWindow.Handle == window.Handle)
                {
                    continue;
                }
                icon = GetIconFromWindow <TIcon>(otherWindow, useLargeIcons);
                if (icon != null)
                {
                    return(icon);
                }
            }
            // Nothing found, REALLY!
            return(default(TIcon));
        }
        /// <summary>
        ///     Get the AppLauncher
        /// </summary>
        /// <returns>IInteropWindow</returns>
        public static IInteropWindow GetAppLauncher()
        {
            // Works only if Windows 8 (or higher)
            if (IsLauncherVisible)
            {
                return(null);
            }
            var appLauncher = User32Api.FindWindow(ApplauncherClass, null);

            if (appLauncher != IntPtr.Zero)
            {
                return(InteropWindowFactory.CreateFor(appLauncher));
            }
            return(null);
        }
Exemple #9
0
        public void Startup()
        {
            var uiSynchronizationContext = SynchronizationContext.Current;

            var keyHandler = new KeyCombinationHandler(_pipConfiguration.HotKey)
            {
                CanRepeat     = false,
                IsPassThrough = false
            };

            KeyboardHook.KeyboardEvents
            .Where(keyHandler)
            .SubscribeOn(uiSynchronizationContext)
            .ObserveOn(uiSynchronizationContext)
            .Subscribe(keyboardHookEventArgs =>
            {
                // Get the current active window
                var pipSource = InteropWindowQuery.GetForegroundWindow();
                while (pipSource.GetParent() != IntPtr.Zero)
                {
                    pipSource = InteropWindowFactory.CreateFor(pipSource.GetParent());
                }

                // If there is already a form, close it and remove it from the dictionary
                if (_thumbnailForms.TryGetValue(pipSource.Handle, out var thumbnailForm))
                {
                    thumbnailForm.Close();
                    _thumbnailForms.Remove(pipSource.Handle);
                    return;
                }

                // Check if we have a location available
                if (!_locationPool.HasAvailable)
                {
                    return;
                }
                thumbnailForm = new ThumbnailForm(_pipConfiguration, _locationPool, pipSource.Handle, uiSynchronizationContext);
                _thumbnailForms[pipSource.Handle] = thumbnailForm;
                thumbnailForm.Show();
            });
        }
Exemple #10
0
        /// <summary>
        /// Change the thumbnail settings
        /// </summary>
        private void UpdateThumbnail()
        {
            // Retrieve the current information about the window, this could changed
            var interopWindow = InteropWindowFactory.CreateFor(_hWnd).Fill();
            var sourceBounds  = interopWindow.Info.Value.Bounds;

            Opacity = Math.Max((byte)0x01, _pipConfiguration.Opacity) / 255d;
            // Prepare the displaying of the Thumbnail
            var props = new DwmThumbnailProperties
            {
                Opacity = _pipConfiguration.Opacity,
                Visible = true,
                SourceClientAreaOnly = _pipConfiguration.SourceClientAreaOnly,
                // This is the size of the DMW Thumbnail
                Destination = new NativeRect(0, 0, Width, Height),
                // Here it would be possible to select only a part of the window, but this is slightly tricky of someone resizes the window
                Source = new NativeRect(0, 0, sourceBounds.Width, sourceBounds.Height)
            };

            Dwm.DwmUpdateThumbnailProperties(_phThumbnail, ref props);
        }
Exemple #11
0
        /// <summary>
        ///     This is called indirectly from the context menu "Preferences"
        /// </summary>
        public void ShowSetting()
        {
            // The new MVVM Configuration
            if (!_configViewModel.IsActive)
            {
                _windowManager.ShowDialog(_configViewModel);
            }

            if (Application.OpenForms.OfType <SettingsForm>().Any())
            {
                // TODO: Await?
                InteropWindowFactory.CreateFor(_settingsForm.Handle).ToForegroundAsync();
            }
            else
            {
                if (_settingsForm.ShowDialog() == DialogResult.OK)
                {
                    InitializeQuickSettingsMenu();
                }
            }
        }
Exemple #12
0
        private async Task TestWinEventHook()
        {
            // This takes care of having a WinProc handler, to make sure the messages arrive
            var winProcHandler = WinProcHandler.Instance;
            // This buffers the observable
            var replaySubject = new ReplaySubject <IInteropWindow>();

            var winEventObservable = WinEventHook.WindowTileChangeObservable()
                                     .Select(info => InteropWindowFactory.CreateFor(info.Handle).Fill())
                                     .Where(interopWindow => !string.IsNullOrEmpty(interopWindow?.Caption))
                                     .Subscribe(interopWindow =>
            {
                Log.Debug().WriteLine("Window title change: Process ID {0} - Title: {1}", interopWindow.Handle, interopWindow.Caption);
                replaySubject.OnNext(interopWindow);
            }, exception => Log.Error().WriteLine("An error occured", exception));
            await Task.Delay(100);

            // Start a process to test against
            using (var process = Process.Start("notepad.exe"))
            {
                try
                {
                    // Make sure it's started
                    Assert.NotNull(process);
                    // Wait until the process started it's message pump (listening for input)
                    process.WaitForInputIdle();
                    User32Api.SetWindowText(process.MainWindowHandle, "TestWinEventHook - Test");

                    // Find the belonging window
                    var notepadWindow = await replaySubject.Where(info => info != null && info.ProcessId == process.Id).FirstAsync();

                    Assert.Equal(process.Id, notepadWindow?.ProcessId);
                }
                finally
                {
                    winEventObservable.Dispose();
                    process?.Kill();
                }
            }
        }
Exemple #13
0
 public void ShowAbout()
 {
     if (_aboutForm != null)
     {
         // TODO: Await?
         InteropWindowFactory.CreateFor(_aboutForm.Handle).ToForegroundAsync();
     }
     else
     {
         try
         {
             using (_aboutForm = new AboutForm())
             {
                 _aboutForm.ShowDialog(this);
             }
         }
         finally
         {
             _aboutForm = null;
         }
     }
 }
 /// <summary>
 ///     Factory method to create a InteropWindow for the supplied WindowForm
 /// </summary>
 /// <param name="form">Form</param>
 /// <returns>InteropWindow</returns>
 public static InteropWindow AsInteropWindow(this Form form)
 {
     return(InteropWindowFactory.CreateFor(form.Handle));
 }
Exemple #15
0
        /// <summary>
        ///     update the frame, this only invalidates
        /// </summary>
        protected override void Animate()
        {
            var lastPos = _cursorPos;

            _cursorPos = _mouseMovePos;

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

            var lastWindow     = SelectedCaptureWindow;
            var horizontalMove = false;
            var verticalMove   = false;

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

            if (UsedCaptureMode == CaptureMode.Region && _mouseDown)
            {
                _captureRect = new NativeRect(_cursorPos.X, _cursorPos.Y, _mX - _cursorPos.X, _mY - _cursorPos.Y).Normalize();
            }

            // Iterate over the found windows and check if the current location is inside a window
            var cursorPosition = Cursor.Position;

            SelectedCaptureWindow = null;


            // Store the top window
            IInteropWindow selectedTopWindow = null;

            foreach (var window in _windows)
            {
                if (window.Handle == Handle)
                {
                    // Ignore us
                    continue;
                }
                if (!window.GetInfo().Bounds.Contains(cursorPosition))
                {
                    continue;
                }

                selectedTopWindow     = window;
                SelectedCaptureWindow = window;

                // Only go over the children if we are in window mode
                if (CaptureMode.Window != UsedCaptureMode)
                {
                    break;
                }

                // Find the child window which is under the mouse
                // Start with the parent, drill down
                var selectedChildWindow = window;
                // TODO: Limit the levels we go down?
                do
                {
                    // Drill down, via the ZOrder
                    var tmpChildWindow = selectedChildWindow
                                         .GetZOrderedChildren()
                                         .FirstOrDefault(interopWindow => interopWindow.GetInfo().Bounds.Contains(cursorPosition));

                    if (tmpChildWindow == null)
                    {
                        break;
                    }
                    selectedChildWindow = tmpChildWindow;
                } while (true);

                // Assign the found child window
                SelectedCaptureWindow = selectedChildWindow;

                break;
            }

            // Test if something changed
            if (SelectedCaptureWindow != null && !SelectedCaptureWindow.Equals(lastWindow))
            {
                _capture.CaptureDetails.Title = selectedTopWindow.Text;
                _capture.CaptureDetails.AddMetaData("windowtitle", selectedTopWindow.Text);
                if (UsedCaptureMode == CaptureMode.Window)
                {
                    // Recreate the WindowScroller, if this is enabled, so we can detect if we can scroll
                    if (Conf.IsScrollingCaptureEnabled)
                    {
                        WindowScroller = SelectedCaptureWindow.GetWindowScroller(ScrollBarTypes.Vertical);
                        if (WindowScroller == null)
                        {
                            foreach (var interopWindow in SelectedCaptureWindow.GetChildren())
                            {
                                interopWindow.Dump();
                            }

                            WindowScroller = SelectedCaptureWindow.GetChildren().Select(child => child.GetWindowScroller(ScrollBarTypes.Vertical)).FirstOrDefault(scroller => scroller != null);
                        }
                    }

                    // We store the bound of the selected (child) window
                    // If it's maximized we take the client-bounds, otherwise we have parts we should not copy.
                    if (SelectedCaptureWindow.IsMaximized())
                    {
                        _captureRect = SelectedCaptureWindow.GetInfo().ClientBounds;
                    }
                    else
                    {
                        _captureRect = SelectedCaptureWindow.GetInfo().Bounds;
                    }

                    // Make sure the bounds fit to it's parent, some windows are bigger than their parent
                    // But only for non popups
                    if (!SelectedCaptureWindow.GetInfo().Style.HasFlag(WindowStyleFlags.WS_POPUP))
                    {
                        var parent = SelectedCaptureWindow.GetParent();
                        while (parent != IntPtr.Zero)
                        {
                            var parentWindow = InteropWindowFactory.CreateFor(parent);
                            _captureRect = _captureRect.Intersect(parentWindow.GetInfo().Bounds);
                            parent       = parentWindow.GetParent();
                        }
                    }

                    // As the ClientRectangle is in screen coordinates and not in bitmap coordinates, we need to correct.
                    _captureRect = _captureRect.Offset(-_capture.ScreenBounds.Location.X, -_capture.ScreenBounds.Location.Y);
                }
            }

            NativeRectFloat invalidateRectangle;

            if (_mouseDown && UsedCaptureMode != CaptureMode.Window)
            {
                var x1 = Math.Min(_mX, lastPos.X);
                var x2 = Math.Max(_mX, lastPos.X);
                var y1 = Math.Min(_mY, lastPos.Y);
                var 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
                var textForWidth  = Math.Max(Math.Abs(_mX - _cursorPos.X), Math.Abs(_mX - lastPos.X));
                var textForHeight = Math.Max(Math.Abs(_mY - _cursorPos.Y), Math.Abs(_mY - lastPos.Y));

                using (var rulerFont = new Font(FontFamily.GenericSansSerif, 8))
                {
                    var textWidth = TextRenderer.MeasureText(textForWidth.ToString(CultureInfo.InvariantCulture), rulerFont);
                    x1 -= textWidth.Width + 15;

                    var textHeight = TextRenderer.MeasureText(textForHeight.ToString(CultureInfo.InvariantCulture), rulerFont);
                    y1 -= textHeight.Height + 10;
                }
                invalidateRectangle = new Rectangle(x1, y1, x2 - x1, y2 - y1);
                Invalidate(invalidateRectangle);
            }
            else if (UsedCaptureMode != CaptureMode.Window)
            {
                var allScreenBounds = WindowCapture.GetScreenBounds();

                allScreenBounds = allScreenBounds.MoveTo(WindowCapture.GetLocationRelativeToScreenBounds(allScreenBounds.Location));
                if (verticalMove)
                {
                    // Before
                    invalidateRectangle = new NativeRect(allScreenBounds.Left, lastPos.Y - 2, Width + 2, 45).Normalize();
                    Invalidate(invalidateRectangle);
                    // After
                    invalidateRectangle = new NativeRect(allScreenBounds.Left, _cursorPos.Y - 2, Width + 2, 45).Normalize();
                    Invalidate(invalidateRectangle);
                }
                if (horizontalMove)
                {
                    // Before
                    invalidateRectangle = new NativeRect(lastPos.X - 2, allScreenBounds.Top, 75, Height + 2).Normalize();
                    Invalidate(invalidateRectangle);
                    // After
                    invalidateRectangle = new NativeRect(_cursorPos.X - 2, allScreenBounds.Top, 75, Height + 2).Normalize();
                    Invalidate(invalidateRectangle);
                }
            }
            else if (SelectedCaptureWindow != null && !SelectedCaptureWindow.Equals(lastWindow))
            {
                // Window changed, animate from current to newly selected window
                _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 animation needs to be drawn
            if (IsAnimating(_windowAnimator))
            {
                invalidateRectangle = _windowAnimator.Current.Inflate(safetySize, safetySize);
                Invalidate(invalidateRectangle);
                invalidateRectangle = _windowAnimator.Next().Inflate(safetySize, safetySize);
                Invalidate(invalidateRectangle);
                // Check if this was the last of the windows animations in the normal region capture.
                if (UsedCaptureMode != CaptureMode.Window && !IsAnimating(_windowAnimator))
                {
                    Invalidate();
                }
            }

            if (_zoomAnimator != null && (IsAnimating(_zoomAnimator) || UsedCaptureMode != CaptureMode.Window))
            {
                // Make sure we invalidate the old zoom area
                invalidateRectangle = _zoomAnimator.Current.Offset(lastPos);
                Invalidate(invalidateRectangle);
                // Only verify if we are really showing the zoom, not the outgoing animation
                if (Conf.ZoomerEnabled && UsedCaptureMode != 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
                invalidateRectangle = IsAnimating(_zoomAnimator) ? _zoomAnimator.Next() : _zoomAnimator.Current;
                Invalidate(invalidateRectangle.Offset(_cursorPos));
            }
            // Force update "now"
            Update();
        }
Exemple #16
0
 /// <summary>
 ///     Factory method to create a InteropWindow for the supplied Window
 /// </summary>
 /// <param name="window">Window</param>
 /// <returns>InteropWindow</returns>
 public static InteropWindow AsInteropWindow(this Window window)
 {
     return(InteropWindowFactory.CreateFor(window.GetHandle()));
 }
        /// <summary>
        ///     Helper method which will retrieve the IHTMLDocument2 for the supplied window,
        ///     or return the first if none is supplied.
        /// </summary>
        /// <param name="browserWindow">The InteropWindow to get the IHTMLDocument2 for</param>
        /// <returns>DocumentContainer</returns>
        private static DocumentContainer CreateDocumentContainer(IInteropWindow browserWindow)
        {
            DocumentContainer returnDocumentContainer = null;
            InteropWindow     returnWindow            = null;
            IHTMLDocument2    returnDocument2         = null;
            // alternative if no match
            InteropWindow  alternativeReturnWindow    = null;
            IHTMLDocument2 alternativeReturnDocument2 = null;

            // Find the IE windows
            foreach (var ieWindow in GetIeWindows())
            {
                Log.Debug().WriteLine("Processing {0} - {1}", ieWindow.Classname, ieWindow.Text);

                Accessible ieAccessible = null;
                var        directUiwd   = IEHelper.GetDirectUi(ieWindow);
                if (directUiwd != null)
                {
                    ieAccessible = new Accessible(directUiwd.Handle);
                }
                if (ieAccessible == null)
                {
                    if (browserWindow != null)
                    {
                        Log.Info().WriteLine("Active Window is {0}", browserWindow.Text);
                    }
                    if (!ieWindow.Equals(browserWindow))
                    {
                        Log.Warn().WriteLine("No ieAccessible for {0}", ieWindow.Text);
                        continue;
                    }
                    Log.Debug().WriteLine("No ieAccessible, but the active window is an IE window: {0}, ", ieWindow.Text);
                }

                try
                {
                    // Get the Document
                    var document2 = GetHtmlDocument(ieWindow);
                    if (document2 == null)
                    {
                        continue;
                    }

                    // Get the content window handle for the shellWindow.Document
                    var oleWindow           = (IOleWindow)document2;
                    var contentWindowHandle = IntPtr.Zero;
                    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/
                        var document4 = (IHTMLDocument4)document2;

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

            // 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
                try
                {
                    returnDocumentContainer = new DocumentContainer(returnDocument2, returnWindow);
                }
                catch (Exception e)
                {
                    Log.Error().WriteLine(null, "Major problem: Problem retrieving Document.");
                    Log.Error().WriteLine(e);
                }
            }

            if (returnDocumentContainer == null && alternativeReturnDocument2 != null)
            {
                // As it doesn't have focus, make sure it's active
                alternativeReturnWindow.Restore();
                alternativeReturnWindow.GetParent();
                // Create the container
                try
                {
                    returnDocumentContainer = new DocumentContainer(alternativeReturnDocument2, alternativeReturnWindow);
                }
                catch (Exception e)
                {
                    Log.Error().WriteLine(null, "Major problem: Problem retrieving Document.");
                    Log.Error().WriteLine(e);
                }
            }
            return(returnDocumentContainer);
        }
Exemple #18
0
        /// <summary>
        ///     The OAuth code receiver
        /// </summary>
        /// <param name="authorizeMode">which of the AuthorizeModes was used to call the method</param>
        /// <param name="codeReceiverSettings"></param>
        /// <param name="cancellationToken">CancellationToken</param>
        /// <returns>Dictionary with values</returns>
        public async Task <IDictionary <string, string> > ReceiveCodeAsync(AuthorizeModes authorizeMode, ICodeReceiverSettings codeReceiverSettings,
                                                                           CancellationToken cancellationToken = default)
        {
            // Force OOB Uri, if nothing is set
            if (string.IsNullOrEmpty(codeReceiverSettings.RedirectUrl))
            {
                switch (authorizeMode)
                {
                case AuthorizeModes.OutOfBound:
                    codeReceiverSettings.RedirectUrl = "urn:ietf:wg:oauth:2.0:oob";
                    break;

                case AuthorizeModes.OutOfBoundAuto:
                    codeReceiverSettings.RedirectUrl = "urn:ietf:wg:oauth:2.0:oob:auto";
                    break;

                default:
                    throw new NotSupportedException($"Only {AuthorizeModes.OutOfBound} and {AuthorizeModes.OutOfBoundAuto} are supported modes for this receiver");
                }
            }

            var uriBuilder = new UriBuilder(codeReceiverSettings.AuthorizationUri)
            {
                Query = codeReceiverSettings.AuthorizationUri.QueryToKeyValuePairs()
                        .Select(x => new KeyValuePair <string, string>(x.Key, x.Value.FormatWith(codeReceiverSettings)))
                        .ToQueryString()
            };

            // Get the formatted FormattedAuthUrl
            var authorizationUrl = uriBuilder.Uri;

            Log.Debug().WriteLine("Opening a browser with: {0}", authorizationUrl.AbsoluteUri);
            // Open the url in the default browser
            var processStartInfo = new ProcessStartInfo(authorizationUrl.AbsoluteUri)
            {
                CreateNoWindow  = true,
                UseShellExecute = true
            };

            Process.Start(processStartInfo);

            Log.Debug().WriteLine("Waiting until a window gets a title with the state {0}", codeReceiverSettings.State);
            // Wait until a window get's a title which contains the state object
            var title = await WinEventHook.WindowTileChangeObservable()
                        .Select(info => InteropWindowFactory.CreateFor(info.Handle).Fill())
                        .Where(interopWindow => !string.IsNullOrEmpty(interopWindow?.Caption))
                        .Where(interopWindow => interopWindow.Caption.Contains(codeReceiverSettings.State))
                        // Skip temporary titles, where the redirect URL os briefly seen
                        .Where(interopWindow => interopWindow?.Caption.Contains(codeReceiverSettings.RedirectUrl) != true)
                        .Select(interopWindow => interopWindow.Caption)
                        .Take(1).ToTask(cancellationToken);

            Log.Debug().WriteLine("Got title {0}", title);
            if (string.IsNullOrEmpty(title))
            {
                return(new Dictionary <string, string>());
            }

            var match = QueryPartOfTitleRegEx.Match(title);

            if (!match.Success)
            {
                return(UriParseExtensions.QueryStringToDictionary(title));
            }

            var queryParameters = match.Groups["query"]?.Value;

            if (string.IsNullOrEmpty(queryParameters))
            {
                return(new Dictionary <string, string>());
            }
            Log.Debug().WriteLine("Query parameters: {0}", queryParameters);
            // Return result of the listening
            return(UriParseExtensions.QueryStringToDictionary(queryParameters));
        }
Exemple #19
0
 public static void InsertIntoNewDocument(string tmpFile, string address, string tooltip)
 {
     using (var wordApplication = GetOrCreateWordApplication())
     {
         if (wordApplication == null)
         {
             return;
         }
         wordApplication.Visible = true;
         wordApplication.Activate();
         // Create new Document
         object template        = string.Empty;
         object newTemplate     = false;
         object documentType    = 0;
         object documentVisible = true;
         using (var documents = wordApplication.Documents)
         {
             using (var wordDocument = documents.Add(ref template, ref newTemplate, ref documentType, ref documentVisible))
             {
                 using (var selection = wordApplication.Selection)
                 {
                     // Add Picture
                     using (var shape = AddPictureToSelection(selection, tmpFile))
                     {
                         if (!string.IsNullOrEmpty(address))
                         {
                             var screentip = Type.Missing;
                             if (!string.IsNullOrEmpty(tooltip))
                             {
                                 screentip = tooltip;
                             }
                             try
                             {
                                 using (var hyperlinks = wordDocument.Hyperlinks)
                                 {
                                     hyperlinks.Add(shape, screentip, Type.Missing, screentip, Type.Missing, Type.Missing);
                                 }
                             }
                             catch (Exception e)
                             {
                                 Log.Warn().WriteLine("Couldn't add hyperlink for image: {0}", e.Message);
                             }
                         }
                     }
                 }
                 try
                 {
                     wordDocument.Activate();
                 }
                 catch
                 {
                     // ignored
                 }
                 try
                 {
                     using (var activeWindow = wordDocument.ActiveWindow)
                     {
                         activeWindow.Activate();
                         var hWnd = activeWindow.Hwnd;
                         if (hWnd > 0)
                         {
                             // TODO: Await?
                             InteropWindowFactory.CreateFor(new IntPtr(hWnd)).ToForegroundAsync();
                         }
                     }
                 }
                 catch
                 {
                     // ignored
                 }
             }
         }
     }
 }
Exemple #20
0
 /// <summary>
 ///     Internal method for the insert
 /// </summary>
 /// <param name="wordApplication"></param>
 /// <param name="wordDocument"></param>
 /// <param name="tmpFile"></param>
 /// <param name="address">link for the image</param>
 /// <param name="tooltip">tooltip of the image</param>
 /// <returns></returns>
 internal static bool InsertIntoExistingDocument(IWordApplication wordApplication, IWordDocument wordDocument, string tmpFile, string address, string tooltip)
 {
     // Bug #1517: image will be inserted into that document, where the focus was last. It will not inserted into the chosen one.
     // Solution: Make sure the selected document is active, otherwise the insert will be made in a different document!
     try
     {
         wordDocument.Activate();
     }
     catch
     {
         // ignored
     }
     using (var selection = wordApplication.Selection)
     {
         if (selection == null)
         {
             Log.Info().WriteLine("No selection to insert {0} into found.", tmpFile);
             return(false);
         }
         // Add Picture
         using (var shape = AddPictureToSelection(selection, tmpFile))
         {
             if (!string.IsNullOrEmpty(address))
             {
                 var screentip = Type.Missing;
                 if (!string.IsNullOrEmpty(tooltip))
                 {
                     screentip = tooltip;
                 }
                 try
                 {
                     using (var hyperlinks = wordDocument.Hyperlinks)
                     {
                         hyperlinks.Add(shape, screentip, Type.Missing, screentip, Type.Missing, Type.Missing);
                     }
                 }
                 catch (Exception e)
                 {
                     Log.Warn().WriteLine("Couldn't add hyperlink for image: {0}", e.Message);
                 }
             }
         }
         try
         {
             using (var activeWindow = wordDocument.ActiveWindow)
             {
                 activeWindow.Activate();
                 using (var activePane = activeWindow.ActivePane)
                 {
                     using (var view = activePane.View)
                     {
                         view.Zoom.Percentage = 100;
                     }
                 }
             }
         }
         catch (Exception e)
         {
             Log.Warn().WriteLine("Couldn't set zoom to 100, error: {0}", e.InnerException?.Message ?? e.Message);
         }
         try
         {
             wordApplication.Activate();
         }
         catch
         {
             // ignored
         }
         try
         {
             using (var activeWindow = wordDocument.ActiveWindow)
             {
                 activeWindow.Activate();
                 var hWnd = activeWindow.Hwnd;
                 if (hWnd > 0)
                 {
                     // TODO: Await?
                     InteropWindowFactory.CreateFor(new IntPtr(hWnd)).ToForegroundAsync();
                 }
             }
         }
         catch
         {
             // ignored
         }
         return(true);
     }
 }
        /// <summary>
        /// Create the full-blown Clip object
        /// </summary>
        /// <param name="clipboardUpdateInformation">ClipboardContents</param>
        /// <returns>Clip</returns>
        private Clip CreateClip(ClipboardUpdateInformation clipboardUpdateInformation)
        {
            if (clipboardUpdateInformation.OwnerHandle == IntPtr.Zero)
            {
                // TODO: Handle "0" here!!!
                Log.Warn().WriteLine("Clipboard content is owned by process 0");
            }
            var interopWindow = InteropWindowFactory.CreateFor(clipboardUpdateInformation.OwnerHandle);

            // Make sure we use the parent window (top level) for the title.
            IInteropWindow toplevelWindow = interopWindow;
            var            parent         = toplevelWindow.GetParent();

            while (true)
            {
                if (parent == IntPtr.Zero)
                {
                    break;
                }
                toplevelWindow = toplevelWindow?.GetParentWindow();
                parent         = toplevelWindow.GetParent();
            }
            var  caption = toplevelWindow.GetCaption();
            Clip clip;

            using (var process = Process.GetProcessById(interopWindow.GetProcessId()))
            {
                // Make sure we got something, when the caption is emtry up to now
                if (string.IsNullOrEmpty(caption))
                {
                    caption = process.MainWindowTitle;
                }

                // Try to create the product name
                string productName = process.ProcessName;

                try
                {
                    var versionInfo = FileVersionInfo.GetVersionInfo(process.MainModule.FileName);
                    productName = versionInfo.ProductName;
                }
                catch (Win32Exception ex)
                {
                    // This happens with elevated processes
                    Log.Warn().WriteLine(ex, "Problem retrieving process information for a process with ID {0} and name {1}", process.Id, process.ProcessName);
                }

                clip = new Clip
                {
                    WindowTitle          = caption,
                    OwnerIcon            = interopWindow.GetIcon <BitmapSource>(true) ?? toplevelWindow.GetIcon <BitmapSource>(true),
                    SessionId            = _currentSession.Id,
                    ProcessName          = process.ProcessName,
                    ProductName          = productName,
                    OriginalWindowHandle = clipboardUpdateInformation.OwnerHandle,
                    SequenceNumber       = clipboardUpdateInformation.Id,
                    OriginalFormats      = clipboardUpdateInformation.Formats.ToList()
                };
            }

            using (var clipboardAccessToken = ClipboardNative.Access())
            {
                clip.Filenames = clipboardAccessToken.GetFilenames().ToList();
                if (clip.OriginalFormats.Contains("CF_UNICODETEXT"))
                {
                    clip.ClipboardText = clipboardAccessToken.GetAsUnicodeString();
                }

                foreach (var format in clipboardUpdateInformation.Formats)
                {
                    if (!_dopyConfiguration.IncludeFormats.Contains(format))
                    {
                        continue;
                    }
                    clip.Formats.Add(format);
                    using var clipboardStream = clipboardAccessToken.GetAsStream(format);
                    var memoryStream = new MemoryStream((int)clipboardStream.Length);
                    clipboardStream.CopyTo(memoryStream);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    clip.Contents[format] = memoryStream;
                }
            }
            return(clip);
        }