예제 #1
0
		public KeyEventArgs (KeyboardDevice keyboard, PresentationSource inputSource,
				     int timestamp, Key key)
			: base (keyboard, timestamp)
		{
			this.inputSource = inputSource;
			this.key = key;
		}
예제 #2
0
        public KeyEventArgs(KeyboardDevice keyboard, PresentationSource inputSource, int timestamp, Key key) : base(keyboard, timestamp)
        {
            if (inputSource == null)
                throw new ArgumentNullException("inputSource");

            if (!Keyboard.IsValidKey(key))
                throw new System.ComponentModel.InvalidEnumArgumentException("key", (int)key, typeof(Key));

            _inputSource = inputSource;

            _realKey = key;
            _isRepeat = false;

            // Start out assuming that this is just a normal key.
            MarkNormal();
        }
        public RawMouseInputReport(
            InputMode mode,
            int timestamp, 
            PresentationSource inputSource,
            RawMouseActions actions, 
            int x, 
            int y, 
            int wheel, 
            IntPtr extraInformation) : base(inputSource, InputType.Mouse, mode, timestamp)
        {
            if (!IsValidRawMouseActions(actions))
                throw new System.ComponentModel.InvalidEnumArgumentException("actions", (int)actions, typeof(RawMouseActions));

            /* we pass a null state from MouseDevice.PreProcessorInput, so null is valid value for state */
            _actions = actions;
            _x = x;
            _y = y;
            _wheel = wheel;
            _extraInformation = new SecurityCriticalData<IntPtr>(extraInformation);
        }
예제 #4
0
 private void InitializeWindowSource(object sender, EventArgs e)
 {
     hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource;
     hwndSource.AddHook(new HwndSourceHook(WndProc));
 }
예제 #5
0
        /// <summary>
        /// Maps GPIOs to Buttons processable by Microsoft.SPOT.Presentation.
        /// </summary>
        /// <param name="source"></param>
        public GPIOButtonInputProvider(PresentationSource source)
        {
            // Set the input source.
            this.source = source;

            // Register the object as an input source with the input manager and
            // get back an InputProviderSite object.  The InputProviderSite
            // object forwards the input report to the input manager.  The input
            // manager then places the input in the staging area.
            site = InputManager.CurrentInputManager.RegisterInputProvider(this);

            // Create a delegate that refers to the InputProviderSite object's
            // ReportInput method.
            callback = new DispatcherOperationCallback(delegate(object report)
            {
                InputReportArgs args = (InputReportArgs)report;
                return(site.ReportInput(args.Device, args.Report));
            });
            Dispatcher = Dispatcher.CurrentDispatcher;

            // Create a hardware provider.
            HardwareProvider hwProvider = new HardwareProvider();

            // Create the pins that are needed for the buttons.  Default their
            // values for the emulator.
            Cpu.Pin pinLeft   = Cpu.Pin.GPIO_Pin0;
            Cpu.Pin pinRight  = Cpu.Pin.GPIO_Pin1;
            Cpu.Pin pinUp     = Cpu.Pin.GPIO_Pin2;
            Cpu.Pin pinSelect = Cpu.Pin.GPIO_Pin3;
            Cpu.Pin pinDown   = Cpu.Pin.GPIO_Pin4;

            // Use the hardware provider to get the pins.  If the left pin is
            // not set, assume none of the pins are set and set the left pin
            // back to the default emulator value.
            if ((pinLeft = hwProvider.GetButtonPins(Button.VK_LEFT)) ==
                Cpu.Pin.GPIO_NONE)
            {
                pinLeft = Cpu.Pin.GPIO_Pin0;
            }
            else
            {
                pinRight  = hwProvider.GetButtonPins(Button.VK_RIGHT);
                pinUp     = hwProvider.GetButtonPins(Button.VK_UP);
                pinSelect = hwProvider.GetButtonPins(Button.VK_SELECT);
                pinDown   = hwProvider.GetButtonPins(Button.VK_DOWN);
            }

            // Allocate button pads and assign the (emulated) hardware pins as
            // input from specific buttons.
            ButtonPad[] buttons = new ButtonPad[]
            {
                // Associate the buttons with the pins as discovered or set
                // above.
                new ButtonPad(this, Button.VK_LEFT, pinLeft),
                new ButtonPad(this, Button.VK_RIGHT, pinRight),
                new ButtonPad(this, Button.VK_UP, pinUp),
                new ButtonPad(this, Button.VK_SELECT, pinSelect),
                new ButtonPad(this, Button.VK_DOWN, pinDown),
            };

            this.buttons = buttons;
        }
 private void PushMenuMode(bool isAcquireFocusMenuMode)
 {
     this._pushedMenuMode        = PresentationSource.CriticalFromVisual(this);
     this.IsAcquireFocusMenuMode = isAcquireFocusMenuMode;
     InputManager.UnsecureCurrent.PushMenuMode(this._pushedMenuMode);
 }
예제 #7
0
        public MainViewModel()
        {
            // Initilizes PDFNet
            PDFNet.Initialize();

            // Make sure to Terminate any processes
            Application.Current.SessionEnding += Current_SessionEnding;

            // Init all Commands
            CMDOpenDocument = new Relaycommand(OpenDocument);
            CMDNextPage     = new Relaycommand(NextPage);
            CMDPreviousPage = new Relaycommand(PreviousPage);

            // Annotations
            CMDAnottateText        = new Relaycommand(AddTextSample);
            CMDFreeTextCreate      = new Relaycommand(AddFreeTextSample);
            CMDSelectText          = new Relaycommand(SelectText);
            CMDSquareCreate        = new Relaycommand(AddSquareAnnotation);
            CMDArrowCreate         = new Relaycommand(AddArrowAnnotation);
            CMDOvalCreate          = new Relaycommand(AddOvalAnnotation);
            CMDSquigglyCreate      = new Relaycommand(AddSquigglyAnnotation);
            CMDUnderlineCreate     = new Relaycommand(AddUnderlineAnnotation);
            CMDStrikeoutCreate     = new Relaycommand(AddStrikeoutAnnotation);
            CMDTextHighlightCreate = new Relaycommand(AddHighlightAnnotation);
            CMDInkCreate           = new Relaycommand(AddInkAnnotation);

            CMDExit    = new Relaycommand(ExitApp);
            CMDZoomIn  = new Relaycommand(ZoomIn);
            CMDZoomOut = new Relaycommand(ZoomOut);
            CMDUndo    = new Relaycommand(Undo);
            CMDRedo    = new Relaycommand(Redo);

            // Checks the scale factor to determine the right resolution
            PresentationSource source      = PresentationSource.FromVisual(Application.Current.MainWindow);
            double             scaleFactor = 1;

            if (source != null)
            {
                scaleFactor = 1 / source.CompositionTarget.TransformFromDevice.M11;
            }

            // Set working doc to Viewer
            PDFViewer = new PDFViewWPF();
            PDFViewer.PixelsPerUnitWidth = scaleFactor;
            PDFViewer.SetPagePresentationMode(PDFViewWPF.PagePresentationMode.e_single_continuous);
            PDFViewer.AllowDrop = true;

            // PDF Viewer Events subscription
            PDFViewer.MouseLeftButtonDown += PDFView_MouseLeftButtonDown;
            PDFViewer.Drop += PDFViewer_Drop;

            // Enable access to the Tools available
            _toolManager = new ToolManager(PDFViewer);
            _toolManager.AnnotationAdded   += _toolManager_AnnotationAdded;
            _toolManager.AnnotationRemoved += _toolManager_AnnotationRemoved;

            // Load PDF file
            PDFDoc doc = new PDFDoc("./Resources/GettingStarted.pdf");

            doc.InitSecurityHandler();
            _undoManager = doc.GetUndoManager();
            PDFViewer.SetDoc(doc);
        }
예제 #8
0
        public static Point TransformFromDeviceDPI(this Visual visual, Point pt)
        {
            Matrix m = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;

            return(new Point(pt.X * m.M11, pt.Y * m.M22));
        }
예제 #9
0
        void ApplyRegion(Rect wndRect)
        {
            if (!this.CanTransform())
            {
                return;
            }

            wndRect = new Rect(
                this.TransformFromDeviceDPI(wndRect.TopLeft),
                this.TransformFromDeviceDPI(wndRect.Size));

            _lastApplyRect = wndRect;

            if (PresentationSource.FromVisual(this) == null)
            {
                return;
            }


            if (_dockingManager != null)
            {
                List <Rect> otherRects = new List <Rect>();

                foreach (Window fl in Window.GetWindow(_dockingManager).OwnedWindows)
                {
                    //not with myself!
                    if (fl == this)
                    {
                        continue;
                    }

                    if (!fl.IsVisible)
                    {
                        continue;
                    }

                    //Issue 11545, thx to SrdjanPolic
                    Rect flRect = new Rect(
                        PointFromScreen(new Point(fl.Left, fl.Top)),
                        PointFromScreen(new Point(fl.Left + fl.RestoreBounds.Width, fl.Top + fl.RestoreBounds.Height)));

                    if (flRect.IntersectsWith(wndRect) && fl.AllowsTransparency == false)
                    {
                        otherRects.Add(Rect.Intersect(flRect, wndRect));
                    }

                    //Rect flRect = new Rect(
                    //    PointFromScreen(new Point(fl.Left, fl.Top)),
                    //    PointFromScreen(new Point(fl.Left + fl.Width, fl.Top + fl.Height)));

                    //if (flRect.IntersectsWith(wndRect))
                    //    otherRects.Add(Rect.Intersect(flRect, wndRect));
                }

                IntPtr hDestRegn = InteropHelper.CreateRectRgn(
                    (int)wndRect.Left,
                    (int)wndRect.Top,
                    (int)wndRect.Right,
                    (int)wndRect.Bottom);

                foreach (Rect otherRect in otherRects)
                {
                    IntPtr otherWin32Rect = InteropHelper.CreateRectRgn(
                        (int)otherRect.Left,
                        (int)otherRect.Top,
                        (int)otherRect.Right,
                        (int)otherRect.Bottom);

                    InteropHelper.CombineRgn(hDestRegn, hDestRegn, otherWin32Rect, (int)InteropHelper.CombineRgnStyles.RGN_DIFF);
                }


                InteropHelper.SetWindowRgn(new WindowInteropHelper(this).Handle, hDestRegn, true);
            }
        }
예제 #10
0
 private void OnPaintSurface(object sender, SkiaSharp.Views.Desktop.SKPaintSurfaceEventArgs e)
 {
     scaleFactor = (float)PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice.M11;
     figureSize  = new SKSize(e.Info.Width / scaleFactor, e.Info.Height / scaleFactor);
     figure.Render(e.Surface.Canvas, figureSize);
 }
예제 #11
0
 internal void SetActiveSource(PresentationSource source)
 {
     this.ActiveSource = source;
 }
        private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handeled)
        {
            switch (msg)
            {
            case WM_GETMINMAXINFO:
                WmGetMinMaxInfo(hwnd, lParam);
                handeled = true;
                break;

            case WM_WINDOWPOSCHANGING:
                WINDOWPOS pos = (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));

                if ((pos.flags & 0x0002) != 0)
                {
                    return(IntPtr.Zero);
                }

                Window wnd = (Window)HwndSource.FromHwnd(hwnd).RootVisual;
                if (wnd == null)
                {
                    return(IntPtr.Zero);
                }

                bool changedPos = false;

                PresentationSource source = PresentationSource.FromVisual(this);

                double wpfDpi = 96;

                double dpiX = wpfDpi;
                double dpiY = wpfDpi;

                if (source != null)
                {
                    dpiX = wpfDpi * source.CompositionTarget.TransformToDevice.M11;
                    dpiY = wpfDpi * source.CompositionTarget.TransformToDevice.M22;
                }

                int minWidth = (int)Math.Round(this.MinWidth / 96 * dpiX, 0);

                if (pos.cx < minWidth)
                {
                    pos.cx     = minWidth;
                    changedPos = true;
                }

                int minHeight = (int)Math.Round(this.MinHeight / 96 * dpiY, 0);

                if (pos.cy < minHeight)
                {
                    pos.cy     = minHeight;
                    changedPos = true;
                }

                if (!changedPos)
                {
                    return(IntPtr.Zero);
                }

                Marshal.StructureToPtr(pos, lParam, true);
                handeled = true;
                break;
            }

            return((System.IntPtr) 0);
        }
예제 #13
0
 public Register(Window window)
 {
     hWnd   = new WindowInteropHelper(window).Handle;
     source = PresentationSource.FromVisual(window) as HwndSource;
     source.AddHook(Listener);
 }
예제 #14
0
        protected virtual void Dispose(bool isdisposing)
        {
            //Check if alreadty disposed
            if (Interlocked.Increment(ref disposeCount) == 1)
            {
                // No longer reference event listeners:
                ConsoleMessage      = null;
                FrameLoadStart      = null;
                FrameLoadEnd        = null;
                LoadError           = null;
                LoadingStateChanged = null;
                Rendering           = null;

                // No longer reference handlers:
                this.SetHandlersToNull();

                if (isdisposing)
                {
                    if (BrowserSettings != null)
                    {
                        BrowserSettings.Dispose();
                        BrowserSettings = null;
                    }

                    PresentationSource.RemoveSourceChangedHandler(this, PresentationSourceChangedHandler);

                    // Release internal event listeners:
                    Loaded            -= OnLoaded;
                    GotKeyboardFocus  -= OnGotKeyboardFocus;
                    LostKeyboardFocus -= OnLostKeyboardFocus;

                    // Release internal event listeners for Drag Drop events:
                    DragEnter -= OnDragEnter;
                    DragOver  -= OnDragOver;
                    DragLeave -= OnDragLeave;
                    Drop      -= OnDrop;

                    IsVisibleChanged -= OnIsVisibleChanged;

                    if (tooltipTimer != null)
                    {
                        tooltipTimer.Tick -= OnTooltipTimerTick;
                    }

                    if (CleanupElement != null)
                    {
                        CleanupElement.Unloaded -= OnCleanupElementUnloaded;
                    }

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

                    foreach (var disposable in disposables)
                    {
                        disposable.Dispose();
                    }
                    disposables.Clear();
                    UiThreadRunAsync(() => WebBrowser = null);
                }

                Cef.RemoveDisposable(this);

                RemoveSourceHook();
            }
        }
예제 #15
0
        public ChromiumWebBrowser()
        {
            if (!Cef.IsInitialized && !Cef.Initialize())
            {
                throw new InvalidOperationException("Cef::Initialize() failed");
            }

            BitmapFactory = new BitmapFactory();

            Cef.AddDisposable(this);
            Focusable        = true;
            FocusVisualStyle = null;
            IsTabStop        = true;

            Dispatcher.BeginInvoke((Action)(() => WebBrowser = this));

            Loaded += OnLoaded;

            GotKeyboardFocus  += OnGotKeyboardFocus;
            LostKeyboardFocus += OnLostKeyboardFocus;

            // Drag Drop events
            DragEnter += OnDragEnter;
            DragOver  += OnDragOver;
            DragLeave += OnDragLeave;
            Drop      += OnDrop;

            IsVisibleChanged += OnIsVisibleChanged;

            ToolTip            = toolTip = new ToolTip();
            toolTip.StaysOpen  = true;
            toolTip.Visibility = Visibility.Collapsed;
            toolTip.Closed    += OnTooltipClosed;

            BackCommand       = new DelegateCommand(this.Back, () => CanGoBack);
            ForwardCommand    = new DelegateCommand(this.Forward, () => CanGoForward);
            ReloadCommand     = new DelegateCommand(this.Reload, () => !IsLoading);
            PrintCommand      = new DelegateCommand(this.Print);
            ZoomInCommand     = new DelegateCommand(ZoomIn);
            ZoomOutCommand    = new DelegateCommand(ZoomOut);
            ZoomResetCommand  = new DelegateCommand(ZoomReset);
            ViewSourceCommand = new DelegateCommand(this.ViewSource);
            CleanupCommand    = new DelegateCommand(Dispose);
            StopCommand       = new DelegateCommand(this.Stop);
            CutCommand        = new DelegateCommand(this.Cut);
            CopyCommand       = new DelegateCommand(this.Copy);
            PasteCommand      = new DelegateCommand(this.Paste);
            SelectAllCommand  = new DelegateCommand(this.SelectAll);
            UndoCommand       = new DelegateCommand(this.Undo);
            RedoCommand       = new DelegateCommand(this.Redo);

            managedCefBrowserAdapter = new ManagedCefBrowserAdapter(this, true);

            disposables.Add(new DisposableEventWrapper(this, ActualHeightProperty, OnActualSizeChanged));
            disposables.Add(new DisposableEventWrapper(this, ActualWidthProperty, OnActualSizeChanged));

            ResourceHandlerFactory = new DefaultResourceHandlerFactory();
            BrowserSettings        = new BrowserSettings();

            PresentationSource.AddSourceChangedHandler(this, PresentationSourceChangedHandler);
        }
예제 #16
0
        void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (Dispatcher.Thread != Thread.CurrentThread)
            {
                Dispatcher.BeginInvoke(new EventHandler <ElapsedEventArgs>(Timer_Elapsed), new object[] { sender, e });
                return;
            }
            try
            {
                Point curMousePos = m_lastItemOver != null?Win32Calls.GetPosition(m_lastItemOver) : new Point(-1, -1);

                if (m_lastItemOver != null && new Rect(0, 0, m_lastItemOver.ActualWidth, m_lastItemOver.ActualHeight).Contains(curMousePos))
                {
                    TimeSpan ts = DateTime.Now - m_timerTime;
                    if (ts.TotalMilliseconds > 500 || Mouse.LeftButton == MouseButtonState.Pressed)
                    {
                        ShowPopup();
                        m_lastItemOver.IsChecked = true;
                        m_lastItemOver           = null;
                        m_timerTime = DateTime.Now;
                    }
                    m_timer.Start();
                }
                else
                {
                    var app = Application.Current;
                    if (app == null)
                    {
                        return;
                    }

                    var window = app.MainWindow;
                    if (window == null || !window.IsActive)
                    {
                        return;
                    }

                    if (PART_Popup.IsOpen && !PART_Popup.Resizing)
                    {
                        var pt32 = new Windows.POINT();
                        Win32Calls.GetCursorPos(ref pt32);
                        Point  mousePos = new Point(pt32.x, pt32.y);
                        Point  pos      = PointToScreen(new Point(0, 0));
                        Matrix m        = PresentationSource.FromVisual(Window.GetWindow(this)).CompositionTarget.TransformToDevice;
                        if (m != Matrix.Identity)
                        {
                            m.Invert();
                            mousePos = m.Transform(mousePos);
                            pos      = m.Transform(pos);
                        }
                        switch (TabsPlacement)
                        {
                        case System.Windows.Controls.Dock.Top:
                            pos.Y += ActualHeight;
                            break;

                        case System.Windows.Controls.Dock.Bottom:
                            pos.Y -= PART_Popup.Height;
                            break;

                        case System.Windows.Controls.Dock.Left:
                            pos.X += ActualWidth;
                            break;

                        case System.Windows.Controls.Dock.Right:
                            pos.X -= PART_Popup.Width;
                            break;
                        }
                        bool  b2      = new Rect(pos.X, pos.Y, PART_Popup.Width, PART_Popup.Height).Contains(mousePos);
                        Point posThis = Win32Calls.GetPosition(this);
                        bool  b3      = new Rect(0, 0, ActualWidth, ActualHeight).Contains(posThis);
                        if (!b2 && !b3)
                        {
                            TimeSpan ts = DateTime.Now - m_timerTime;
                            if (ts.TotalMilliseconds > 1000)
                            {
                                // if mouse is outside for more than some time, then collapse this popup
                                ClosePopup();
                            }
                            else
                            {
                                m_timer.Start();
                            }
                        }
                        else
                        {
                            m_timerTime = DateTime.Now;
                            m_timer.Start();
                        }
                    }
                }
            }
            catch (InvalidOperationException)
            {
                // Can be thrown when closing the application and popup is still open...
            }
        }
예제 #17
0
        public static Point TransformFromDevice(this Point point, Visual visual)
        {
            Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;

            return(new Point(point.X * matrix.M11, point.Y * matrix.M22));
        }
예제 #18
0
 private double GetDpiFactor()
 {
     //var currentDPI = (int)Registry.GetValue("HKEY_CURRENT_USER\\Control Panel\\Desktop", "LogPixels", 96);
     //var scale = (float)currentDP == 96 ? 1 : 96/(float)currentDPI;
     return(PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice.M11);
 }
예제 #19
0
        public static Rect TransformFromDevice(this Rect rect, Visual visual)
        {
            Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;

            return(Rect.Transform(rect, matrix));
        }
예제 #20
0
        /// <summary>
        /// Displays the <see cref="TrayPopup"/> control if it was set.
        /// </summary>
        private void ShowTrayPopup(Point cursorPosition)
        {
            if (IsDisposed)
            {
                return;
            }

            // raise preview event no matter whether popup is currently set
            // or not (enables client to set it on demand)
            var args = RaisePreviewTrayPopupOpenEvent();

            if (args.Handled)
            {
                return;
            }

            if (TrayPopup == null)
            {
                return;
            }

            // use absolute position, but place the popup centered above the icon
            TrayPopupResolved.Placement        = PlacementMode.AbsolutePoint;
            TrayPopupResolved.HorizontalOffset = cursorPosition.X;
            TrayPopupResolved.VerticalOffset   = cursorPosition.Y;

            // open popup
            TrayPopupResolved.IsOpen = true;

            IntPtr handle = IntPtr.Zero;

            if (TrayPopupResolved.Child != null)
            {
                // try to get a handle on the popup itself (via its child)
                HwndSource source = (HwndSource)PresentationSource.FromVisual(TrayPopupResolved.Child);
                if (source != null)
                {
                    handle = source.Handle;
                }
            }

            // if we don't have a handle for the popup, fall back to the message sink
            if (handle == IntPtr.Zero)
            {
                handle = messageSink.MessageWindowHandle;
            }

            // activate either popup or message sink to track deactivation.
            // otherwise, the popup does not close if the user clicks somewhere else
            WinApi.SetForegroundWindow(handle);

            // raise attached event - item should never be null unless developers
            // changed the CustomPopup directly...
            if (TrayPopup != null)
            {
                RaisePopupOpenedEvent(TrayPopup);
            }

            // bubble routed event
            RaiseTrayPopupOpenEvent();
        }
예제 #21
0
        public static Size TransformFromDeviceDPI(this Visual visual, Size size)
        {
            Matrix m = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;

            return(new Size(size.Width * m.M11, size.Height * m.M22));
        }
예제 #22
0
 protected override void OnSourceInitialized(EventArgs e)
 {
     base.OnSourceInitialized(e);
     ((HwndSource)PresentationSource.FromVisual(this)).AddHook(myHook);
 }
예제 #23
0
 public static bool CanTransform(this Visual visual)
 {
     return(PresentationSource.FromVisual(visual) != null);
 }
예제 #24
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            Debug.Print("DiffControl OnRender");

#if DEBUG
            MeasureRendeTime();
#endif

            // Fill background
            drawingContext.DrawRectangle(AppSettings.FullMatchBackground, null, new Rect(0, 0, this.ActualWidth, this.ActualHeight));

            if (Lines.Count == 0)
            {
                return;
            }

            typeface = new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, this.FontStretch);

            Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
            dpiScale = 1 / m.M11;

            TextUtils.CreateGlyphRun("W", typeface, this.FontSize, dpiScale, out characterWidth);
            characterHeight = Math.Ceiling(TextUtils.FontHeight(typeface, this.FontSize, dpiScale) / dpiScale) * dpiScale;

            Brush activeDiffBrush = new SolidColorBrush(Color.FromRgb(220, 220, 220));
            activeDiffBrush.Freeze();

            Pen borderPen = new Pen(SystemColors.ScrollBarBrush, RoundToWholePixels(1));
            borderPen.Freeze();
            GuidelineSet borderGuide = CreateGuidelineSet(borderPen);

            textMargin       = RoundToWholePixels(4);
            lineNumberMargin = RoundToWholePixels(characterWidth * Lines.Count.ToString().Length) + (2 * textMargin) + borderPen.Thickness;

            VisibleLines       = (int)(ActualHeight / characterHeight + 1);
            MaxVerialcalScroll = Lines.Count - VisibleLines + 1;

            drawingContext.DrawRectangle(SystemColors.ControlBrush, null, new Rect(0, 0, lineNumberMargin, this.ActualHeight));

            for (int i = 0; i < VisibleLines; i++)
            {
                int lineIndex = i + VerticalOffset;

                if (lineIndex >= Lines.Count)
                {
                    break;
                }

                Line line = Lines[lineIndex];

                // Line Y offset
                drawingContext.PushTransform(new TranslateTransform(0, characterHeight * i));
                {
                    // Draw line number
                    SolidColorBrush lineNumberColor = SystemColors.ControlDarkBrush;

                    if (lineIndex >= CurrentDiff && lineIndex < CurrentDiff + CurrentDiffLength && !Edited)
                    {
                        lineNumberColor = SystemColors.ControlDarkDarkBrush;
                        drawingContext.DrawRectangle(activeDiffBrush, null, new Rect(0, 0, lineNumberMargin, characterHeight));
                    }

                    // Draw line background
                    if (line.Type != TextState.FullMatch)
                    {
                        drawingContext.DrawRectangle(line.BackgroundBrush, null, new Rect(lineNumberMargin, 0, Math.Max(this.ActualWidth - lineNumberMargin, 0), characterHeight));
                    }

                    if (line.LineIndex != null)
                    {
                        GlyphRun rowNumberRun = line.GetRenderedLineIndexText(typeface, this.FontSize, dpiScale, out double rowNumberWidth);

                        drawingContext.PushTransform(new TranslateTransform(lineNumberMargin - rowNumberWidth - textMargin - borderPen.Thickness, 0));
                        drawingContext.DrawGlyphRun(lineNumberColor, rowNumberRun);
                        drawingContext.Pop();
                    }

                    // Text clipping rect
                    drawingContext.PushClip(new RectangleGeometry(new Rect(lineNumberMargin + textMargin, 0, Math.Max(ActualWidth - lineNumberMargin - textMargin * 2, 0), ActualHeight)));
                    {
                        // Line X offset
                        drawingContext.PushTransform(new TranslateTransform(lineNumberMargin + textMargin - HorizontalOffset, 0));
                        {
                            // Draw line
                            if (line.Text != "")
                            {
                                double nextPosition = 0;
                                foreach (TextSegment textSegment in line.TextSegments)
                                {
                                    drawingContext.PushTransform(new TranslateTransform(nextPosition, 0));

                                    GlyphRun segmentRun = textSegment.GetRenderedText(typeface, this.FontSize, dpiScale, AppSettings.ShowWhiteSpaceCharacters, AppSettings.TabSize, out double runWidth);

                                    if (nextPosition - HorizontalOffset < ActualWidth && nextPosition + runWidth - HorizontalOffset > 0)
                                    {
                                        if (line.Type != textSegment.Type && AppSettings.ShowLineChanges)
                                        {
                                            drawingContext.DrawRectangle(textSegment.BackgroundBrush, null, new Rect(nextPosition == 0 ? -textMargin : 0, 0, runWidth + (nextPosition == 0 ? textMargin : 0), characterHeight));
                                        }

                                        drawingContext.DrawGlyphRun(AppSettings.ShowLineChanges ? textSegment.ForegroundBrush : line.ForegroundBrush, segmentRun);
                                    }
                                    nextPosition += runWidth;

                                    drawingContext.Pop();
                                }
                                maxTextwidth = Math.Max(maxTextwidth, nextPosition);
                            }

                            // Draw cursor
                            if (EditMode && this.IsFocused && cursorLine == lineIndex && cursorBlink)
                            {
                                drawingContext.DrawRectangle(Brushes.Black, null, new Rect(CharacterPosition(lineIndex, cursorCharacter), 0, RoundToWholePixels(1), characterHeight));
                            }
                        }
                        drawingContext.Pop();                 // Line X offset
                    }
                    drawingContext.Pop();                     // Text clipping rect

                    // Text area clipping rect
                    drawingContext.PushClip(new RectangleGeometry(new Rect(lineNumberMargin, 0, Math.Max(ActualWidth - lineNumberMargin, 0), ActualHeight)));
                    {
                        // Line X offset 2
                        drawingContext.PushTransform(new TranslateTransform(lineNumberMargin + textMargin - HorizontalOffset, 0));
                        {
                            // Draw selection
                            if (Selection != null && lineIndex >= Selection.TopLine && lineIndex <= Selection.BottomLine)
                            {
                                Rect selectionRect = new Rect(0 - textMargin + HorizontalOffset, 0, this.ActualWidth + HorizontalOffset, characterHeight);
                                if (Selection.TopLine == lineIndex && Selection.TopCharacter > 0)
                                {
                                    selectionRect.X = Math.Max(0, CharacterPosition(lineIndex, Selection.TopCharacter));
                                }
                                if (Selection.BottomLine == lineIndex)
                                {
                                    selectionRect.Width = Math.Max(0, CharacterPosition(lineIndex, Selection.BottomCharacter) - selectionRect.X);
                                }
                                drawingContext.DrawRectangle(AppSettings.SelectionBackground, null, selectionRect);
                            }
                        }
                        drawingContext.Pop();         // Line X offset 2
                    }
                    drawingContext.Pop();             // Text area clipping rect
                }
                drawingContext.Pop();                 // Line Y offset
            }

            // Draw line number border
            drawingContext.PushGuidelineSet(borderGuide);
            {
                drawingContext.DrawLine(borderPen, new Point(lineNumberMargin, -1), new Point(lineNumberMargin, this.ActualHeight));
            }
            drawingContext.Pop();

            TextAreaWidth       = (int)(ActualWidth - lineNumberMargin - (textMargin * 2));
            MaxHorizontalScroll = (int)(maxTextwidth - TextAreaWidth + textMargin);

#if DEBUG
            ReportRenderTime();
#endif
        }
예제 #25
0
        static void Main(string[] args)
        {
            var c = new JSCSolutionsNETCarouselCanvas
            {
                CloseOnClick = false
            };

            c.HideSattelites();


            //c.Container.Effect = new DropShadowEffect();
            //c.Container.BitmapEffect = new DropShadowBitmapEffect();

            //.MoveTo(0, ImageCarouselCanvas.DefaultHeight - 96).SizeTo(ImageCarouselCanvas.DefaultWidth, 96);

            var cc = new Canvas();


            // http://cloudstore.blogspot.com/2008/05/creating-custom-window-style.html
            var wcam = new Window();

            wcam.Background  = Brushes.Transparent;
            wcam.WindowStyle = WindowStyle.None;
            wcam.ResizeMode  = ResizeMode.NoResize;
            wcam.SizeTo(200, 200);
            wcam.AllowsTransparency = true;
            //wcam.Opacity = 0.5;
            wcam.ShowInTaskbar = false;
            wcam.Cursor        = Cursors.Hand;
            wcam.Focusable     = false;
            wcam.Topmost       = true;

            var w = cc.ToWindow();


            w.SizeToContent = SizeToContent.Manual;
            //w.SizeTo(400, 400);
            //w.ToTransparentWindow();


            // http://blog.joachim.at/?p=39
            // http://blogs.msdn.com/changov/archive/2009/01/19/webbrowser-control-on-transparent-wpf-window.aspx
            // http://blogs.interknowlogy.com/johnbowen/archive/2007/06/20/20458.aspx
            w.AllowsTransparency = true;
            w.WindowStyle        = System.Windows.WindowStyle.None;
            w.Focusable          = false;

            //w.Background = new SolidColorBrush(Color.FromArgb(0x20, 0, 0, 0));
            w.Background            = Brushes.Transparent;
            w.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            w.Topmost = true;
            //w.ShowInTaskbar = false;

            var winfoc = new Canvas();



            var winfo = winfoc.ToWindow();

            winfo.AllowsTransparency = true;
            winfo.ShowInTaskbar      = false;
            winfo.WindowStyle        = WindowStyle.None;
            //winfo.Background = Brushes.Transparent;
            winfo.Background = Brushes.Red;
            winfo.Opacity    = 0.3;

            winfo.ResizeMode = ResizeMode.NoResize;

            winfo.SizeToContent = SizeToContent.Manual;
            winfo.Topmost       = true;
            // http://www.squidoo.com/youtubehd



            var NextInputModeEnabled        = false;
            var NextInputModeKeyDownEnabled = false;

            Action <Key> NextInputModeKeyDown = delegate { };

            var CommandKeysEnabled = false;

            #region TopicText
            var TopicText = new System.Windows.Controls.TextBox
            {
                //IsReadOnly = true,
                Background      = Brushes.Transparent,
                BorderThickness = new System.Windows.Thickness(0),
                Foreground      = Brushes.White,
                Effect          = new DropShadowEffect(),
                Text            = "JSC C# Foo Bar",
                //TextDecorations = TextDecorations.Underline,
                FontFamily    = new FontFamily("Verdana"),
                FontSize      = 24,
                TextAlignment = System.Windows.TextAlignment.Right
            };
            #endregion


            #region KeyDown
            InterceptKeys.KeyDown +=
                key =>
            {
                if (key == Key.LeftShift)
                {
                    //w.Background = new SolidColorBrush(Color.FromArgb(2, 0, 0, 0));
                    //w.MakeInteractive(true);
                    NextInputModeEnabled = true;
                }
                else
                {
                    if (NextInputModeEnabled || NextInputModeKeyDownEnabled)
                    {
                        NextInputModeKeyDownEnabled = false;
                        NextInputModeKeyDown(key);
                    }

                    NextInputModeEnabled = false;
                }
            };
            #endregion

            #region KeyUp
            InterceptKeys.KeyUp +=
                key =>
            {
                if (key == Key.CapsLock)
                {
                    CommandKeysEnabled   = !CommandKeysEnabled;
                    TopicText.IsReadOnly = CommandKeysEnabled;
                    TopicText.Select(0, 0);
                }

                if (key == Key.LeftShift)
                {
                    NextInputModeKeyDownEnabled = false;
                }
                else
                {
                }

                NextInputModeEnabled = false;
            };
            #endregion


            var s = 7;

            var ThumbnailSize           = 0.4;
            var CaptionBackgroundHeight = 24;

            #region UpdateChildren
            Action UpdateChildren =
                delegate
            {
                if (w.ActualWidth == 0)
                {
                    return;
                }

                var ss  = s;
                var ss2 = 0;


                Console.WriteLine(
                    new { w.Left, w.Top });

                winfo.MoveTo(w.Left, w.Top).SizeTo(w.ActualWidth, w.ActualHeight);

                if (ThumbnailSize == 1)
                {
                    wcam.Background = Brushes.Black;
                    ss = 0;

                    var qw = w.ActualWidth - ss * 2;
                    var qh = w.ActualHeight - ss * 2;

                    // no status bars or menues please :)

                    wcam.MoveTo(
                        w.Left + ss + ss2,
                        w.Top + (w.ActualHeight - qh * ThumbnailSize - ss) - ss2
                        ).SizeTo(
                        qw * ThumbnailSize,
                        qh * ThumbnailSize
                        );
                }
                else
                {
                    wcam.Background = Brushes.Transparent;

                    //if (w.WindowState == WindowState.Maximized)
                    //{
                    //    ss2 = s;
                    //}

                    var qw = w.ActualWidth - ss * 2;
                    var qh = w.ActualHeight - ss * 2;



                    wcam.MoveTo(w.Left + ss + ss2, w.Top + (w.ActualHeight - qh * ThumbnailSize - ss) - ss2).SizeTo(qw * ThumbnailSize, qh * ThumbnailSize);
                }
            };
            #endregion


            w.LocationChanged +=
                delegate
            {
                UpdateChildren();
            };



            var Borders = Enumerable.Range(1, s * 2).Reverse().Select(
                Width =>
                new
            {
                Width = Width * 2,
                Left  = new Rectangle {
                    Fill = Brushes.Black, Opacity = 0.06
                }.MoveTo(0, 0).AttachTo(winfoc),
                Right = new Rectangle {
                    Fill = Brushes.Black, Opacity = 0.06
                }.MoveTo(0, 0).AttachTo(winfoc),
                Bottom = new Rectangle {
                    Fill = Brushes.Black, Opacity = 0.03
                }.MoveTo(0, 0).AttachTo(winfoc),
                Top = new Rectangle {
                    Fill = Brushes.Black, Opacity = 0.11
                }.MoveTo(0, 0).AttachTo(winfoc)
            }
                ).ToArray();

            var CaptionBackgroundOverlay = new Rectangle
            {
                Fill    = Brushes.Black,
                Opacity = 0.02,
            }.AttachTo(cc);

            var CaptionSysMenuOverlay = new Rectangle
            {
                Fill    = Brushes.Black,
                Opacity = 0.02,
            }.AttachTo(cc).SizeTo(CaptionBackgroundHeight * 4, CaptionBackgroundHeight);

            var ExtraBorderTop = new Rectangle
            {
                Fill    = Brushes.Black,
                Opacity = 0.0,
            }.AttachTo(winfoc);

            var ExtraBorderBottom = new Rectangle
            {
                Fill    = Brushes.Black,
                Opacity = 0.0,
            }.AttachTo(winfoc);

            var CaptionClose = new TextBox
            {
                Foreground      = Brushes.Red,
                FontFamily      = new FontFamily("Webdings"),
                Text            = "r",
                Background      = Brushes.Transparent,
                BorderThickness = new Thickness(0),
                TextAlignment   = System.Windows.TextAlignment.Center,
                Opacity         = 0.5
            }.AttachTo(winfoc);


            var CaptionText = new System.Windows.Controls.TextBox
            {
                IsReadOnly      = true,
                Background      = Brushes.Transparent,
                BorderThickness = new System.Windows.Thickness(0),
                Foreground      = Brushes.White,
                Effect          = new System.Windows.Media.Effects.DropShadowEffect(),
                Text            = "jsc-solutions.net",
                //TextDecorations = TextDecorations.Underline,
                FontFamily    = new FontFamily("Verdana"),
                FontSize      = 16,
                TextAlignment = System.Windows.TextAlignment.Right
            }
            .AttachTo(winfoc);

            TopicText.AttachTo(winfoc);

            #region SetCaption
            Action <string> SetCaption =
                text =>
            {
                if (string.IsNullOrEmpty(text))
                {
                    CaptionText.Text = "jsc-solutions.net";
                }
                else
                {
                    CaptionText.Text = text + " | jsc-solutions.net";
                }
            };
            #endregion



            c.AttachContainerTo(winfoc);

            var ExtraBorderSize = 0.10;


            var Intro = new PromotionBrandIntro.ApplicationCanvas().AttachTo(winfoc);
            Intro.Opacity = 0;

            #region SizeChanged
            Action SizeChanged =
                delegate
            {
                Intro.SizeTo(w.ActualWidth, w.ActualHeight);
                //ink.SizeTo(w.ActualWidth, w.ActualHeight - CaptionBackgroundHeight);

                var CaptionWidth = 200;

                CaptionBackgroundOverlay.MoveTo(w.ActualWidth - CaptionWidth, 0).SizeTo(CaptionWidth, CaptionBackgroundHeight);


                ExtraBorderTop.MoveTo(0, 0).SizeTo(w.ActualWidth, w.ActualHeight * ExtraBorderSize);
                ExtraBorderBottom.MoveTo(0, w.ActualHeight * (1 - ExtraBorderSize)).SizeTo(w.ActualWidth, w.ActualHeight * ExtraBorderSize);

                TopicText.MoveTo(
                    0,
                    w.ActualHeight - 48
                    ).SizeTo(w.ActualWidth - 48, 48);


                if (c != null)
                {
                    c.MoveContainerTo(-200 + 42, -200 + 38);
                }
                Borders.WithEach(k => k.Left.MoveTo(0, 0).SizeTo(k.Width, w.ActualHeight));
                Borders.WithEach(k => k.Right.MoveTo(w.ActualWidth - k.Width, 0).SizeTo(k.Width, w.ActualHeight));
                Borders.WithEach(k => k.Bottom.MoveTo(0, w.ActualHeight - k.Width).SizeTo(w.ActualWidth, k.Width));
                Borders.WithEach(k => k.Top.MoveTo(0, 0).SizeTo(w.ActualWidth, k.Width));
                CaptionText.MoveTo(0, 2).SizeTo(w.ActualWidth - CaptionBackgroundHeight, 32);
                CaptionClose.MoveTo(w.ActualWidth - CaptionBackgroundHeight, s).SizeTo(CaptionBackgroundHeight - s, CaptionBackgroundHeight - s);

                UpdateChildren();
            };
            #endregion

            w.SizeChanged +=
                delegate
            {
                SizeChanged();
            };

            w.StateChanged +=
                delegate
            {
                if (w.WindowState == WindowState.Maximized)
                {
                    w.WindowState = WindowState.Normal;
                }

                SizeChanged();
            };



            #region GetWindows
            Func <IEnumerable <Internal.Window> > GetWindows =
                delegate
            {
                var windows = new List <Internal.Window>();
                Internal.EnumWindows(
                    (IntPtr hwnd, int lParam) =>
                {
                    if (new WindowInteropHelper(wcam).Handle != hwnd &&
                        (Internal.GetWindowLongA(hwnd, Internal.GWL_STYLE) & Internal.TARGETWINDOW) == Internal.TARGETWINDOW
                        )
                    {
                        StringBuilder sb = new StringBuilder(100);
                        Internal.GetWindowText(hwnd, sb, sb.Capacity);

                        windows.Add(
                            new Internal.Window
                        {
                            Handle = hwnd,
                            Title  = sb.ToString()
                        }
                            );
                    }

                    return(true);        //continue enumeration
                }
                    , 0);

                return(windows.OrderBy(k => k.Title));
            };
            #endregion

            var ResetThumbnailSkip = 0;

            Func <Internal.Window> GetCurrentThumbnail = () => GetWindows().AsCyclicEnumerable().Skip(ResetThumbnailSkip).First();

            #region AnimationCompleted
            Intro.AnimationCompleted +=
                delegate
            {
                if (c == null)
                {
                    c = new JSCSolutionsNETCarouselCanvas
                    {
                        CloseOnClick = false
                    }.AttachContainerTo(winfoc);
                    c.HideSattelites();

                    CaptionClose.Show();
                    SizeChanged();
                }
            };
            #endregion


            wcam.SourceInitialized +=
                delegate
            {
                {
                    wcam.MakeInteractive(false);

                    UpdateChildren();
                }



                var thumb = IntPtr.Zero;
                ResetThumbnailSkip = GetWindows().Where(
                    k =>
                    k.Title.Contains("Chrome") ||
                    k.Title.Contains("Studio") ||
                    k.Title.Contains("Minefield")

                    ).TakeWhile(k => k.Handle != Internal.GetForegroundWindow()).Count();


                #region ResetThumbnail
                Action ResetThumbnail =
                    delegate
                {
                    GetCurrentThumbnail().With(
                        shadow =>
                    {
                        //t.Text = shadow.Title;

                        if (thumb != IntPtr.Zero)
                        {
                            Internal.DwmUnregisterThumbnail(thumb);
                        }

                        int i = Internal.DwmRegisterThumbnail(
                            new WindowInteropHelper(wcam).Handle, shadow.Handle, out thumb);

                        #region UpdateThumbnail
                        Action UpdateThumbnail =
                            delegate
                        {
                            if (thumb != IntPtr.Zero)
                            {
                                Internal.PSIZE size;
                                Internal.DwmQueryThumbnailSourceSize(thumb, out size);

                                Internal.DWM_THUMBNAIL_PROPERTIES props = new Internal.DWM_THUMBNAIL_PROPERTIES();

                                props.fVisible              = true;
                                props.dwFlags               = Internal.DWM_TNP_VISIBLE | Internal.DWM_TNP_RECTDESTINATION | Internal.DWM_TNP_OPACITY | Internal.DWM_TNP_SOURCECLIENTAREAONLY;
                                props.opacity               = (byte)((byte)(0x7F) + (byte)((0x80) * (ThumbnailSize)));
                                props.rcDestination         = new Internal.Rect(0, 0, (int)wcam.ActualWidth, (int)wcam.ActualHeight);
                                props.fSourceClientAreaOnly = true;

                                if (size.x < wcam.ActualWidth)
                                {
                                    props.rcDestination.Right = props.rcDestination.Left + size.x;

                                    props.rcDestination.Left  += ((int)wcam.ActualWidth - size.x) / 2;
                                    props.rcDestination.Right += ((int)wcam.ActualWidth - size.x) / 2;
                                }

                                if (size.y < wcam.ActualHeight)
                                {
                                    props.rcDestination.Bottom = props.rcDestination.Top + size.y;

                                    props.rcDestination.Top    += ((int)wcam.ActualHeight - size.y) / 2;
                                    props.rcDestination.Bottom += ((int)wcam.ActualHeight - size.y) / 2;
                                }



                                Internal.DwmUpdateThumbnailProperties(thumb, ref props);
                            }
                        };
                        #endregion


                        (1000 / 15).AtInterval(UpdateThumbnail);

                        wcam.SizeChanged += delegate { UpdateThumbnail(); };
                    }
                        );
                };
                #endregion



                ResetThumbnail();

                NextInputModeKeyDown +=
                    key =>
                {
                    if (key == Key.RightShift)
                    {
                        NextInputModeKeyDownEnabled = true;

                        if (c != null)
                        {
                            CaptionClose.Hide();
                            c.AtClose +=
                                delegate
                            {
                                c.OrphanizeContainer();
                            };
                            c.Close();
                            c = null;
                        }

                        Intro.Background      = Brushes.Transparent;
                        Intro.Overlay.Opacity = 1;
                        Intro.FadeIn(
                            delegate
                        {
                            2000.AtDelay(Intro.PrepareAnimation());
                        }
                            );
                    }

                    if (!CommandKeysEnabled)
                    {
                        if (key == Key.F2)
                        {
                            w.Activate();

                            TopicText.Focusable = true;
                            TopicText.Focus();
                            TopicText.SelectAll();
                        }
                        return;
                    }

                    if (key == Key.Right)
                    {
                        if (w.IsActive)
                        {
                            GetCurrentThumbnail().Activate();
                        }
                        else
                        {
                            NextInputModeKeyDownEnabled = true;
                            ResetThumbnailSkip          = GetWindows().TakeWhile(k => k.Handle != Internal.GetForegroundWindow()).Count();
                            ResetThumbnail();
                        }
                    }

                    if (key == Key.Up)
                    {
                        NextInputModeKeyDownEnabled = true;

                        if (ThumbnailSize < 0.3)
                        {
                            ThumbnailSize = 0.3;
                        }
                        else if (ThumbnailSize < 0.5)
                        {
                            ThumbnailSize = 0.5;
                        }
                        else if (ThumbnailSize < 1)
                        {
                            ThumbnailSize = 1;
                        }
                        else
                        {
                            if (c != null)
                            {
                                CaptionClose.Hide();
                                c.AtClose +=
                                    delegate
                                {
                                    c.OrphanizeContainer();
                                };
                                c.Close();
                                c = null;
                            }
                        }


                        UpdateChildren();
                    }
                    if (key == Key.Down)
                    {
                        NextInputModeKeyDownEnabled = true;
                        if (c == null)
                        {
                            c = new JSCSolutionsNETCarouselCanvas
                            {
                                CloseOnClick = false
                            }.AttachContainerTo(winfoc);
                            CaptionClose.Show();
                        }
                        else if (ThumbnailSize > 0.5)
                        {
                            ThumbnailSize = 0.5;
                        }
                        else if (ThumbnailSize > 0.3)
                        {
                            ThumbnailSize = 0.3;
                        }
                        else if (ThumbnailSize == 0.3)
                        {
                            ThumbnailSize = 0;
                        }

                        SizeChanged();
                    }



                    if (key == Key.Left)
                    {
                        if (w.IsActive)
                        {
                            NextInputModeKeyDownEnabled = true;
                            if (ExtraBorderTop.Opacity == 1)
                            {
                                ExtraBorderTop.Opacity    = 0;
                                ExtraBorderBottom.Opacity = 0;
                            }
                            else
                            {
                                ExtraBorderTop.Opacity    = 1;
                                ExtraBorderBottom.Opacity = 1;
                            }
                        }
                    }
                };
            };

            winfo.SourceInitialized +=
                delegate
            {
                winfo.MakeInteractive(false);
            };

            w.SourceInitialized +=
                delegate
            {
                // http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/61e93dca-e24c-4953-9719-22ce3f705353
                Matrix m  = PresentationSource.FromVisual(w).CompositionTarget.TransformToDevice;
                double dx = m.M11;
                double dy = m.M22;


                w.SizeTo(1280 / dx, 768 / dy);
                w.MoveTo(8, 0);
                SizeChanged();

                wcam.Owner  = w;
                winfo.Owner = w;
                wcam.Show();
                winfo.Show();

                HwndSource hwndSource = (HwndSource)HwndSource.FromVisual(w);
                hwndSource.AddHook(
                    (IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handeled) =>
                {
                    if (msg == 0x0084)         // WM_NCHITTEST
                    {
                        //http://agsmith.wordpress.com/2008/09/16/hit-testing-in-wpf/

                        var p = new
                        {
                            cx = w.ActualWidth - (Internal.LOWORD(lParam) - w.Left),
                            cy = w.ActualHeight - (Internal.HIWORD(lParam) - w.Top),
                            x  = Internal.LOWORD(lParam) - w.Left,
                            y  = Internal.HIWORD(lParam) - w.Top
                        };


                        CaptionText.Text = p.ToString();

                        handeled = true;

                        return((IntPtr)HitTestValues.HTCAPTION);        // HTCAPTION


                        if (false)
                        {
                            if (p.x < s)
                            {
                                if (p.y < s)
                                {
                                    return((IntPtr)HitTestValues.HTTOPLEFT);        // HTCAPTION
                                }
                            }
                            if (p.x < CaptionBackgroundHeight)
                            {
                                if (p.y < CaptionBackgroundHeight)
                                {
                                    return((IntPtr)HitTestValues.HTSYSMENU);        // HTCAPTION
                                }
                            }
                            if (p.cx < CaptionBackgroundHeight)
                            {
                                if (p.y < CaptionBackgroundHeight)
                                {
                                    return((IntPtr)HitTestValues.HTCLOSE);        // HTCAPTION
                                }
                            }
                            if (p.cx < s)
                            {
                                if (p.cy < s)
                                {
                                    return((IntPtr)HitTestValues.HTBOTTOMRIGHT);        // HTCAPTION
                                }
                            }
                            if (p.cx < s)
                            {
                                if (p.y < s)
                                {
                                    return((IntPtr)HitTestValues.HTTOPRIGHT);        // HTCAPTION
                                }
                            }
                            if (p.x < s)
                            {
                                if (p.cy < s)
                                {
                                    return((IntPtr)HitTestValues.HTBOTTOMLEFT);        // HTCAPTION
                                }
                            }
                            if (p.x < s)
                            {
                                return((IntPtr)HitTestValues.HTLEFT);        // HTCAPTION
                            }
                            if (p.y < s)
                            {
                                return((IntPtr)HitTestValues.HTTOP);        // HTCAPTION
                            }
                            if (p.cx < s)
                            {
                                return((IntPtr)HitTestValues.HTRIGHT);        // HTCAPTION
                            }
                            if (p.cy < s)
                            {
                                return((IntPtr)HitTestValues.HTBOTTOM);        // HTCAPTION
                            }
                            if (p.y < CaptionBackgroundHeight)
                            {
                                return((IntPtr)HitTestValues.HTCAPTION);        // HTCAPTION
                            }
                            return((IntPtr)HitTestValues.HTTRANSPARENT);        // HTCAPTION
                        }
                    }
                    return(IntPtr.Zero);
                }

                    );
            };



            InterceptKeys.InternalMain(
                Rehook =>
            {
                w.Deactivated +=
                    delegate
                {
                    TopicText.Focusable = false;
                };
                w.Activated +=
                    delegate
                {
                    //TopicText.Focus();
                    Rehook();
                };

                w.ShowDialog();
            }
                );
        }
예제 #26
0
        public IPresentationSource CreatePresentationSource(UIElement rootElement)
        {
            PresentationSource presentationSource = new PresentationSource(rootElement, HtmlValueConverter.Default);
            presentationSources.Add(presentationSource);

            return presentationSource;
        }
예제 #27
0
        //see: https://stackoverflow.com/questions/4708039/what-event-is-fired-when-a-usercontrol-is-displayed
        private void AppInfoButton_Loaded(object sender, RoutedEventArgs e)
        {
            PresentationSource presentationSource = PresentationSource.FromVisual((Visual)sender);      // Get PresentationSource

            presentationSource.ContentRendered += PresentationSource_ContentRendered;                   // Subscribe to PresentationSource's ContentRendered event
        }
예제 #28
0
        private void HookWin32Message()
        {
            var source = PresentationSource.FromVisual(this) as HwndSource;

            source?.AddHook(WndProc);             // Hook Win32 Messages to method
        }
예제 #29
0
        protected void CreateDrawTextList()
        {
            LastItemRenderTextHeight = 0;
            textDrawLists            = null;
            Matrix m = PresentationSource.FromVisual(Application.Current.MainWindow).CompositionTarget.TransformToDevice;

            if (Items == null)
            {
                return;
            }
            textDrawLists = new List <List <Tuple <Brush, GlyphRun> > >(Items.Count);

            if (ItemFontNormal == null || ItemFontNormal.GlyphType == null ||
                ItemFontTitle == null || ItemFontTitle.GlyphType == null)
            {
                return;
            }
            ItemFontNormal.PrepareCache();
            ItemFontTitle.PrepareCache();

            {
                double          selfLeft     = Canvas.GetLeft(this);
                double          sizeTitle    = Math.Max(Settings.Instance.FontSizeTitle, 1);
                double          sizeNormal   = Math.Max(Settings.Instance.FontSize, 1);
                double          indentTitle  = sizeTitle * 1.7;
                double          indentNormal = IsTitleIndent ? indentTitle : 2;
                SolidColorBrush colorTitle   = CommonManager.Instance.CustTitle1Color;
                SolidColorBrush colorNormal  = CommonManager.Instance.CustTitle2Color;

                foreach (ProgramViewItem info in Items)
                {
                    var textDrawList = new List <Tuple <Brush, GlyphRun> >();
                    textDrawLists.Add(textDrawList);

                    double innerLeft = info.LeftPos + BorderLeftSize / 2;
                    //0.26は細枠線での微調整
                    double innerTop    = info.TopPos + BorderTopSize / 2 - 0.26;
                    double innerWidth  = info.Width - BorderLeftSize;
                    double innerHeight = info.Height - BorderTopSize;
                    double useHeight;

                    //分
                    string min = (info.EventInfo.StartTimeFlag == 0 ? "?" : info.EventInfo.start_time.Minute.ToString("d02"));
                    if (RenderText(min, textDrawList, ItemFontTitle, sizeTitle * 0.95,
                                   innerWidth - 1, innerHeight,
                                   innerLeft + 1, innerTop, out useHeight, colorTitle, m, selfLeft) == false)
                    {
                        info.TitleDrawErr        = true;
                        LastItemRenderTextHeight = info.Height;
                        continue;
                    }

                    //タイトル
                    string title = info.EventInfo.ShortInfo == null ? "" : info.EventInfo.ShortInfo.event_name;
                    if (ReplaceDictionaryTitle != null)
                    {
                        title = CommonManager.ReplaceText(title, ReplaceDictionaryTitle);
                    }
                    if (RenderText(title.Length > 0 ? title : " ", textDrawList, ItemFontTitle, sizeTitle,
                                   innerWidth - sizeTitle * 0.5 - indentTitle, innerHeight,
                                   innerLeft + indentTitle, innerTop, out useHeight, colorTitle, m, selfLeft) == false)
                    {
                        info.TitleDrawErr        = true;
                        LastItemRenderTextHeight = info.Height;
                        continue;
                    }
                    if (info.Height < sizeTitle)
                    {
                        //高さ足りない
                        info.TitleDrawErr = true;
                    }
                    LastItemRenderTextHeight = useHeight + sizeNormal * 0.5;

                    if (info.EventInfo.ShortInfo != null)
                    {
                        //説明
                        string detail = info.EventInfo.ShortInfo.text_char;
                        //詳細
                        detail += ExtInfoMode == false || info.EventInfo.ExtInfo == null ? "" : "\r\n\r\n" + info.EventInfo.ExtInfo.text_char;
                        if (ReplaceDictionaryNormal != null)
                        {
                            detail = CommonManager.ReplaceText(detail, ReplaceDictionaryNormal);
                        }
                        RenderText(detail, textDrawList, ItemFontNormal, sizeNormal,
                                   innerWidth - sizeTitle * 0.5 - indentNormal, innerHeight - LastItemRenderTextHeight,
                                   innerLeft + indentNormal, innerTop + LastItemRenderTextHeight, out useHeight, colorNormal, m, selfLeft);
                        LastItemRenderTextHeight += useHeight + sizeNormal * 0.25;
                    }
                    LastItemRenderTextHeight = Math.Floor(LastItemRenderTextHeight + BorderTopSize + sizeNormal * 0.5);
                    LastItemRenderTextHeight = Math.Min(LastItemRenderTextHeight, info.Height);
                }
            }
        }
예제 #30
0
        private NativeMethods.RECT CalculateAssignedRC(PresentationSource source)
        {
            Rect rectElement = new Rect(RenderSize);
            Rect rectRoot = PointUtil.ElementToRoot(rectElement, this, source);
            Rect rectClient = PointUtil.RootToClient(rectRoot, source);

            // Adjust for Right-To-Left oriented windows
            IntPtr hwndParent = UnsafeNativeMethods.GetParent(_hwnd);
            NativeMethods.RECT rcClient = PointUtil.FromRect(rectClient);
            NativeMethods.RECT rcClientRTLAdjusted = PointUtil.AdjustForRightToLeft(rcClient, new HandleRef(null, hwndParent));

            return rcClientRTLAdjusted;
        }
예제 #31
0
 private void MainWindow_SourceInitialized(object sender, EventArgs e)
 {
     _hwndSource = (HwndSource)PresentationSource.FromVisual(this);
 }
예제 #32
0
파일: TextStore.cs 프로젝트: mind0n/hive
        private void GetVisualInfo(out PresentationSource source, out IWin32Window win32Window, out ITextView view)
        {
            source = PresentationSource.CriticalFromVisual(RenderScope);
            win32Window = source as IWin32Window;

            if (win32Window == null)
            {
                throw new COMException(SR.Get(SRID.TextStore_TS_E_NOLAYOUT), UnsafeNativeMethods.TS_E_NOLAYOUT);
            }

            view = this.TextView;
        }
        public void OnTextAreaTextEnteringEventTest()
        {
            // Arrange
            string pythonCode = "from System.Collections import ArrayList";

            Open(@"core\python\python.dyn");

            var nodeView  = NodeViewWithGuid("3bcad14e-d086-4278-9e08-ed2759ef92f3");
            var nodeModel = nodeView.ViewModel.NodeModel as PythonNodeBase;

            Assert.NotNull(nodeModel);

            var scriptWindow = EditPythonCode(nodeView, View);
            var codeEditor   = FindCodeEditor(scriptWindow);

            scriptWindow.editText.TextArea.TextEntering += TextArea_TextEntering;
            codeEditor.SelectionStart = 0;
            codeEditor.Text           = pythonCode;
            codeEditor.Focus();

            //This will generate the event of going to the end of the line
            var textArea = Keyboard.FocusedElement;

            textArea.RaiseEvent(new KeyEventArgs(
                                    Keyboard.PrimaryDevice,
                                    PresentationSource.FromVisual(codeEditor),
                                    0,
                                    Key.End)
            {
                RoutedEvent = Keyboard.KeyDownEvent
            }
                                );

            //This will pop up the automcompletion list info
            textArea.RaiseEvent(
                new TextCompositionEventArgs(
                    Keyboard.PrimaryDevice,
                    new TextComposition(InputManager.Current, textArea, "."))
            {
                RoutedEvent = TextCompositionManager.TextInputEvent
            }
                );

            //This will indicate to the python script to import everything from the ArrayList module and will raise the OnTextAreaTextEntering entering to a specific code section
            textArea.RaiseEvent(
                new TextCompositionEventArgs(
                    Keyboard.PrimaryDevice,
                    new TextComposition(InputManager.Current, textArea, "*"))
            {
                RoutedEvent = TextCompositionManager.TextInputEvent
            }
                );

            //Act
            DispatcherUtil.DoEvents();

            scriptWindow.editText.TextArea.TextEntering -= TextArea_TextEntering;
            //Assert
            //Validates that OnTextAreaTextEntering event was executed.
            Assert.IsNotNull(codeEditor.Text);
            Assert.That(codeEditor.Text, Is.EqualTo(pythonCode + ".*"));
            Assert.IsTrue(bTextEnteringEventRaised);
        }
예제 #34
0
        public static Size TransformFromDevice(this Size size, Visual visual)
        {
            Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;

            return(new Size(size.Width * matrix.M11, size.Height * matrix.M22));
        }
예제 #35
0
 static Rect ElementToRoot(Rect rectElement, Visual element, PresentationSource presentationSource)
 {
     return(element.TransformToAncestor(presentationSource.RootVisual).TransformBounds(rectElement));
 }
예제 #36
0
        private static void GetClippedPositionOffsets(TextEditor This, ITextPointer position, LogicalDirection direction,
                                                      out double horizontalOffset, out double verticalOffset)
        {
            // GetCharacterRect will return the position that base on UiScope.
            Rect positionRect = position.GetCharacterRect(direction);

            // Get the base offsets for our ContextMenu.
            horizontalOffset = positionRect.X;
            verticalOffset   = positionRect.Y + positionRect.Height;

            // Clip to the child render scope.
            FrameworkElement element = This.TextView.RenderScope as FrameworkElement;

            if (element != null)
            {
                GeneralTransform transform = element.TransformToAncestor(This.UiScope);
                if (transform != null)
                {
                    ClipToElement(element, transform, ref horizontalOffset, ref verticalOffset);
                }
            }

            // Clip to parent visuals.
            // This is unintuitive -- you might expect parents to have increasingly
            // larger viewports.  But any parent that behaves like a ScrollViewer
            // will have a smaller view port that we need to clip against.
            for (Visual visual = This.UiScope; visual != null; visual = VisualTreeHelper.GetParent(visual) as Visual)
            {
                element = visual as FrameworkElement;
                if (element != null)
                {
                    GeneralTransform transform = visual.TransformToDescendant(This.UiScope);
                    if (transform != null)
                    {
                        ClipToElement(element, transform, ref horizontalOffset, ref verticalOffset);
                    }
                }
            }

            // Clip to the window client rect.
            PresentationSource source = PresentationSource.CriticalFromVisual(This.UiScope);
            IWin32Window       window = source as IWin32Window;

            if (window != null)
            {
                IntPtr hwnd = IntPtr.Zero;
                new UIPermission(UIPermissionWindow.AllWindows).Assert(); // BlessedAssert
                try
                {
                    hwnd = window.Handle;
                }
                finally
                {
                    CodeAccessPermission.RevertAssert();
                }

                NativeMethods.RECT rc = new NativeMethods.RECT(0, 0, 0, 0);
                SafeNativeMethods.GetClientRect(new HandleRef(null, hwnd), ref rc);

                // Convert to mil measure units.
                Point minPoint = new Point(rc.left, rc.top);
                Point maxPoint = new Point(rc.right, rc.bottom);

                CompositionTarget compositionTarget = source.CompositionTarget;
                minPoint = compositionTarget.TransformFromDevice.Transform(minPoint);
                maxPoint = compositionTarget.TransformFromDevice.Transform(maxPoint);

                // Convert to local coordinates.
                GeneralTransform transform = compositionTarget.RootVisual.TransformToDescendant(This.UiScope);
                if (transform != null)
                {
                    transform.TryTransform(minPoint, out minPoint);
                    transform.TryTransform(maxPoint, out maxPoint);

                    // Finally, do the clip.
                    horizontalOffset = ClipToBounds(minPoint.X, horizontalOffset, maxPoint.X);
                    verticalOffset   = ClipToBounds(minPoint.Y, verticalOffset, maxPoint.Y);
                }

                // ContextMenu code takes care of clipping to desktop.
            }
        }
예제 #37
0
파일: TextStore.cs 프로젝트: mind0n/hive
        private static UnsafeNativeMethods.RECT TransformRootRectToScreenCoordinates(Point milPointTopLeft, Point milPointBottomRight, IWin32Window win32Window, PresentationSource source)
        {
            UnsafeNativeMethods.RECT rect;
            NativeMethods.POINT clientPoint;
            CompositionTarget compositionTarget;

            rect = new UnsafeNativeMethods.RECT();

            // Transform to device units.
            compositionTarget = source.CompositionTarget;
            milPointTopLeft = compositionTarget.TransformToDevice.Transform(milPointTopLeft);
            milPointBottomRight = compositionTarget.TransformToDevice.Transform(milPointBottomRight);

            IntPtr hwnd = IntPtr.Zero;
            new UIPermission(UIPermissionWindow.AllWindows).Assert(); // BlessedAssert
            try
            {
                hwnd = win32Window.Handle;
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }

            // Transform to screen coords.
            clientPoint = new NativeMethods.POINT();
            UnsafeNativeMethods.ClientToScreen(new HandleRef(null, hwnd), /* ref by interop */ clientPoint);

            rect.left = (int)(clientPoint.x + milPointTopLeft.X);
            rect.right = (int)(clientPoint.x + milPointBottomRight.X);
            rect.top = (int)(clientPoint.y + milPointTopLeft.Y);
            rect.bottom = (int)(clientPoint.y + milPointBottomRight.Y);
            return rect;
        }
예제 #38
0
 private void ResizeWindow(ResizeDirection direction) => SendMessage(((HwndSource)PresentationSource.FromVisual(this)).Handle, 0x112, (IntPtr)(61440 + direction), IntPtr.Zero);
        internal RawStylusSystemGestureInputReport(
            InputMode           mode, 
            int           	    timestamp, 
            PresentationSource  inputSource,
            PenContext          penContext, 
            int                 tabletId,
            int                 stylusDeviceId,
            SystemGesture       systemGesture,
            int                 gestureX, 
            int                 gestureY,
            int                 buttonState) 
            : base( mode, timestamp, inputSource, 
                    penContext, RawStylusActions.SystemGesture,
                    tabletId, stylusDeviceId, new int[] {}) 
        {
            if (!RawStylusSystemGestureInputReport.IsValidSystemGesture(systemGesture, true, true))
            {
                throw new InvalidEnumArgumentException(SR.Get( SRID.Enum_Invalid, "systemGesture")); 
            }
 
            _id             = systemGesture; 
            _gestureX       = gestureX;
            _gestureY       = gestureY; 
            _buttonState    = buttonState;
        }
예제 #40
0
		protected Point GetClientPosition (PresentationSource presentationSource)
		{
			throw new NotImplementedException ();
		}