/// <summary> /// Get corrected cursor coordinates relative to Visual</summary> /// <param name="relativeTo">Visual to get coordinates relative to</param> /// <returns>Cursor position in current coordinate system of the Visual</returns> public static Point CorrectGetPosition(Visual relativeTo) { var w32Mouse = new User32.POINT(); GetCursorPos(ref w32Mouse); return(relativeTo.PointFromScreen(new Point(w32Mouse.X, w32Mouse.Y))); }
public static double CalcDistance(this User32.POINT pt1, User32.POINT pt2) { var x = Math.Abs(pt1.X - pt2.X) / (double)App.Instance.DpiX * 2.54 / 100.0; var y = Math.Abs(pt1.Y - pt2.Y) / (double)App.Instance.DpiY * 2.54 / 100.0; return(Math.Sqrt(x * x + y * y)); }
/// Client座標系の座標をWindowタイプ別にScreen座標系に変換する public static ScreenPoint ClientToScreen(WindowTypes windowType, UIntPtr window, int clientX, int clientY) { switch (windowType) { case WindowTypes.Normal: { Debug.Assert(Common.Utilities.IsWindowValid(window), "Invalid Window", "ClientToScreen"); User32.POINT windowPoint = new User32.POINT { X = clientX, Y = clientY }; User32.ClientToScreen(window, ref windowPoint); return(new ScreenPoint(windowPoint.X, windowPoint.Y)); } case WindowTypes.DXGI: { // VirtualScreen座標なので補正を戻す return(new ScreenPoint(clientX + User32.GetSystemMetrics(User32.SM_XVIRTUALSCREEN), clientY + User32.GetSystemMetrics(User32.SM_YVIRTUALSCREEN))); } case WindowTypes.Desktop: { // Screen座標系なのでそのまま返す return(new ScreenPoint(clientX, clientY)); } default: Debug.Fail("switch"); throw new System.ArgumentException(); } }
public override Rectangle RectangleToClient(Rectangle r) { var pts = new User32.POINT[2]; pts[0].x = r.Left; pts[0].y = r.Top; pts[1].x = r.Right; pts[1].y = r.Bottom; User32.MapWindowPoints(IntPtr.Zero, Handle, pts, pts.Length); return(Rectangle.FromLTRB(pts[0].x, pts[0].y, pts[1].x, pts[1].y)); }
public static Rectangle ScreenBoundsFromPoint(Point point) { var pt = new User32.POINT() { X = point.X, Y = point.Y }; var info = new User32.MonitorInfoEx();//new User32.MONITORINFOEX(); info.Init(); User32.GetMonitorInfo(User32.MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST), ref info); return(Rectangle.FromLTRB(info.Monitor.Left, info.Monitor.Top, info.Monitor.Right, info.Monitor.Bottom)); }
private Image GetDesktopBitmap(IntPtr hWnd, User32.RECT rect) { var crect = new User32.RECT(rect.Left, rect.Top, rect.Right, rect.Bottom); var p = new User32.POINT(0, 0); User32.ClientToScreen(hWnd, ref p); crect.Top = p.Y; crect.Left = p.X; crect.Bottom = p.Y + crect.Bottom; crect.Right = p.X + crect.Right; if (VisibilityTester.HitTest(crect, hWnd, new[] { new Point(p.X + 1, p.Y + 1) }, IntPtr.Zero)) { return GetDesktopBitmap(hWnd); } return null; }
/// <include file='doc\Screen.uex' path='docs/doc[@for="Screen.FromPoint"]/*' /> /// <devdoc> /// <para> /// Retrieves a <see cref='Screen'/> /// for the monitor that contains the specified point. /// /// </para> /// </devdoc> public static Screen FromPoint(Point point) { if (multiMonitorSupport) { var pt = new User32.POINT() { X = point.X, Y = point.Y }; return(new Screen(User32.MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST))); } else { return(new Screen((IntPtr)PRIMARY_MONITOR)); } }
private int CorrectYifNeeded(User32.POINT ptCurr, Rect rFrom, Rect rTo, User32.POINT delta) { if (ptCurr.Y > rTo.Top && ptCurr.Y < rTo.Bottom) { return(ptCurr.Y + delta.Y); //no correction needed } const int offsetY = 80; int y = (int)rTo.Top + offsetY; if (ptCurr.Y >= rTo.Bottom) { y = (int)(rTo.Bottom - offsetY); } return(y); }
private Image GetDesktopBitmap(IntPtr hWnd, User32.RECT rect) { var crect = new User32.RECT(rect.Left, rect.Top, rect.Right, rect.Bottom); var p = new User32.POINT(0, 0); User32.ClientToScreen(hWnd, ref p); crect.Top = p.Y; crect.Left = p.X; crect.Bottom = p.Y + crect.Bottom; crect.Right = p.X + crect.Right; if (VisibilityTester.HitTest(crect, hWnd, new[] { new Point(p.X + 1, p.Y + 1) }, IntPtr.Zero)) { return(GetDesktopBitmap(hWnd)); } return(null); }
public override Point PointToClient(Point p) { var pt = new User32.POINT(); pt.x = p.X; pt.y = p.Y; bool result = User32.ScreenToClient(Handle, ref pt); if (!result) { throw new Win32Exception(); } return(new Point(pt.x, pt.y)); }
private int CalcProportionalY(User32.POINT ptCurr, Rect rFrom, Rect rTo, User32.POINT delta) { Debug.WriteLine("Current Point: {0}", ptCurr); double srcRatioFromTop = (ptCurr.Y - rFrom.Top) / rFrom.Height; if (srcRatioFromTop < 0 || srcRatioFromTop >= 1) { srcRatioFromTop = 0.5; } double dstY = rTo.Top + srcRatioFromTop * rTo.Height; Debug.WriteLine("SrcRatio: {0:0.00} DstHeight:{1:0.0} DstY: {2:0.0}", srcRatioFromTop, rTo.Height, dstY); return((int)dstY); }
public void Clear() { CursorPosition = new User32.POINT { X = 0, Y = 0 }; hWnd = (IntPtr)0; WindowText = string.Empty; WindowClassName = "N/A"; WindowPath = "N/A"; hWndParent = (IntPtr)0; ParentText = "N/A"; ParentClassName = "N/A"; }
FrameworkElement GetHitTarget(GazeEventArgs ev) { var pt = new User32.POINT() { X = (int)ev.Screen.X, Y = (int)ev.Screen.Y }; var hwnd = User32.WindowFromPoint(pt); if ((_hwndMain != hwnd) && (!User32.IsChild(_hwndMain, hwnd)) && _hwndCursor != hwnd && _hwndMouseListner != hwnd) { return(_offScreenElement); } if ((ev.Scaled.X < 0) || (ev.Scaled.Y < 0) || (ev.Scaled.X > 1) || (ev.Scaled.Y > 1)) { return(_offScreenElement); } FrameworkElement hitTarget; try { _nextVisualHit = null; Point windowPoint = _window.PointFromScreen(ev.Screen); VisualTreeHelper.HitTest(_window, null, new HitTestResultCallback(GazeHitTestResultFilter), new PointHitTestParameters(windowPoint)); hitTarget = (_nextVisualHit != null) ? GetRootElement(_nextVisualHit) : null; } catch (System.InvalidOperationException ex) { _trace.TraceInformation("EXCEPTION: {0}", ex.Message); hitTarget = null; } if (hitTarget == null) { hitTarget = _offScreenElement; } return(hitTarget); }
//if screens are different height - move mouse vertical proportionally to border private User32.POINT CorrectIntoOtherScreenProportionally(User32.POINT ptPrev, User32.POINT ptCurr, int screenSrcIndex) { User32.POINT delta = ptCurr - ptPrev; Rect rFrom = _screens[screenSrcIndex].DeviceBounds; Rect rTo; int maxDistanceFromBorder = 1 + Math.Abs(delta.X); if (Math.Abs(ptCurr.X - _screens[screenSrcIndex].DeviceBounds.Left) < maxDistanceFromBorder) //close to left side { if (screenSrcIndex == 0 || delta.X >= 0) //left most or move away { return(new User32.POINT()); } rTo = _screens[screenSrcIndex - 1].DeviceBounds; Debug.WriteLine("LEFT => Mouse Position:{0} Delta:{1}", ptCurr, delta); } else if (Math.Abs(ptCurr.X - _screens[screenSrcIndex].DeviceBounds.Right) < maxDistanceFromBorder) //close to right side { if (screenSrcIndex == _screens.Count - 1 || delta.X <= 0) //right most or move away { return(new User32.POINT()); } rTo = _screens[screenSrcIndex + 1].DeviceBounds; Debug.WriteLine("RIGHT => Mouse Position:{0} Delta:{1}", ptCurr, delta); } else { //Debug.WriteLine("MIDDLE => Mouse Position:{0} Delta:{1}", ptCurr, delta); return(new User32.POINT()); } int dstY = CalcProportionalY(ptCurr, rFrom, rTo, delta); //int dstY = CorrectYIfNeeded(ptCurr, rFrom, rTo, delta); User32.POINT corrected = new User32.POINT(ptCurr.X + delta.X, dstY); Debug.WriteLine("Corrected Mouse Position: {0} Delta:{1}", corrected, delta); return(corrected); }
/// <summary> /// Gets a segment of the desktop as an image. /// </summary> /// <returns>A <see cref="System.Drawing.Image"/> containg an image of the full desktop.</returns> public Image GetDesktopBitmap(IntPtr hWnd) { Image capture = null; try { var crect = new User32.RECT(); User32.GetClientRect(hWnd, ref crect); var p = new User32.POINT(0, 0); User32.ClientToScreen(hWnd, ref p); crect.Top = p.Y; crect.Left = p.X; crect.Bottom = p.Y + crect.Bottom; crect.Right = p.X + crect.Right; capture = this.GetDesktopBitmap(crect); return(capture); } finally { } }
private void OnMouseMove(MouseHook.MouseEventArgs32 e) { User32.POINT ptCurr = e.MessageData.pt; if (ptCurr.Equals(_prev)) { //Debug.WriteLine("SKIP => Mouse Position:{0}", _prev); return; //already been there } User32.POINT ptPrev = _prev; _prev = e.MessageData.pt; if (IsButtonDown || _screens.Count == 1 || !MouseHook.Hook.Enabled) { return; //ignore dragging or if one sceen only or if not enabled } int screenSrcIndex = WpfScreen.ScreenIndexFromPoint(ptPrev.X, ptPrev.Y, _screens); if (screenSrcIndex < 0) //point out of screens { return; } int screenDstIndex = WpfScreen.ScreenIndexFromPoint(ptCurr.X, ptCurr.Y, _screens); if (screenSrcIndex == screenDstIndex) { return; } User32.POINT ptCorrected = CorrectIntoOtherScreenProportionally(ptPrev, ptCurr, screenSrcIndex); if (ptCorrected.X != 0 || ptCorrected.Y != 0) { _prev = ptCorrected; //already handled User32.SetCursorPos(ptCorrected.X, ptCorrected.Y); } }
private IntPtr HookMouseCallbackImplementation(int nCode, IntPtr wParam, IntPtr lParam) { if (RemoteControlActive) { var wmMouse = (User32.MouseMessage)wParam; if (wmMouse == User32.MouseMessage.WM_MOUSEMOVE) { User32.POINT lpPoint = (User32.POINT)Marshal.PtrToStructure(lParam, typeof(User32.POINT)); MouseMoveActivityEventArgs args = new MouseMoveActivityEventArgs(); args.DiffX = lpPoint.x - baseMouseX; args.DiffY = lpPoint.y - baseMouseY; OnMouseMoveActivity(args); } if (wmMouse == User32.MouseMessage.WM_MOUSEWHEEL) { User32.MSLLHOOKSTRUCT mSLLHOOKSTRUCT = (User32.MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(User32.MSLLHOOKSTRUCT)); var wheelData = ((short)(mSLLHOOKSTRUCT.mouseData >> 16)); MouseWheelActivityEventArgs args = new MouseWheelActivityEventArgs(); args.RotationDown = (wheelData > 0) ? false : true; OnMouseWheelActivity(args); } if (wmMouse == User32.MouseMessage.WM_LBUTTONDOWN) { MouseButtonActivityEventArgs args = new MouseButtonActivityEventArgs(); args.IsPressed = true; args.KeyCode = KeyCode.LButton; OnMouseButtonActivity(args); } if (wmMouse == User32.MouseMessage.WM_LBUTTONUP) { MouseButtonActivityEventArgs args = new MouseButtonActivityEventArgs(); args.IsPressed = false; args.KeyCode = KeyCode.LButton; OnMouseButtonActivity(args); } if (wmMouse == User32.MouseMessage.WM_RBUTTONDOWN) { MouseButtonActivityEventArgs args = new MouseButtonActivityEventArgs(); args.IsPressed = true; args.KeyCode = KeyCode.RButton; OnMouseButtonActivity(args); } if (wmMouse == User32.MouseMessage.WM_RBUTTONUP) { MouseButtonActivityEventArgs args = new MouseButtonActivityEventArgs(); args.IsPressed = false; args.KeyCode = KeyCode.RButton; OnMouseButtonActivity(args); } if (wmMouse == User32.MouseMessage.WM_MBUTTONDOWN) { MouseButtonActivityEventArgs args = new MouseButtonActivityEventArgs(); args.IsPressed = true; args.KeyCode = KeyCode.MButton; OnMouseButtonActivity(args); } if (wmMouse == User32.MouseMessage.WM_MBUTTONUP) { MouseButtonActivityEventArgs args = new MouseButtonActivityEventArgs(); args.IsPressed = false; args.KeyCode = KeyCode.MButton; OnMouseButtonActivity(args); } // bo nie puszczamy dalej, tylko wysłane zostało na port szeregowy return((IntPtr)1); } // puszczamy dalej (nie łapiemy) do obsługi return(User32.CallNextHookEx(globalMouseHookId, nCode, wParam, lParam)); }
internal static extern bool GetCursorPos(ref User32.POINT pt);
// NOTE: I don't think this supports fullscreen applications. So keep that in mind. public Overlay() { InitializeComponent(); Process[] procs = Process.GetProcessesByName(processName); if (procs.Length > 1) { MessageBox.Show("Error 1\nMultiple processes \"" + processName + "\" found. Program this yourself.", "Multiple processes", MessageBoxButtons.OK, MessageBoxIcon.Error); // TODO: Support choosing between multiple windows! Environment.Exit(0); // Kill it } else if (procs.Length > 0) { ourHandle = procs[0].MainWindowHandle; // NOTE: Sometimes might just be "procs[0].Handle". Change below too if needed. } if (ourHandle == IntPtr.Zero) { List <Process> procs2 = new List <Process>(Process.GetProcesses()); foreach (Process p in procs2) { if (p.MainWindowTitle.StartsWith(processName)) { if ((ourHandle = p.MainWindowHandle) != IntPtr.Zero) // NOTE: Sometimes might just be "p.Handle" { break; } } } } if (ourHandle == IntPtr.Zero) // No window? { MessageBox.Show("Error 2\nNo Process \"" + processName + "\" found.", "No process found", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); } //Make the window's border completely transparant User32.SetWindowLong(this.Handle, GWL_EXSTYLE, (IntPtr)(User32.GetWindowLong(this.Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED ^ WS_EX_TRANSPARENT)); // Set the Alpha on the Whole Window (Black) to 255 (solid) //SetLayeredWindowAttributes(this.Handle, (uint)System.Drawing.ColorTranslator.ToWin32(Color.Magenta), 255, LWA_ALPHA); // Color example User32.SetLayeredWindowAttributes(this.Handle, 0, 255, LWA_ALPHA); // The frame is black due to aliasing or something causing some outline issues sometimes. I think. I can't remember, this code is old. I just want it for future reference. User32.RECT windowRect = new User32.RECT(); User32.GetClientRect(ourHandle, ref windowRect); User32.POINT pt = new User32.POINT(); User32.ClientToScreen(ourHandle, ref pt); this.Width = windowRect.right - windowRect.left; this.Height = windowRect.bottom - windowRect.top; this.Location = new Point(pt.x, pt.y); // Create a margin (the whole form) marg = new Margins { Left = 0, Top = 0, Right = this.Width, Bottom = this.Height }; // Obviously this will have to move if you want your form to resize // Init DirectX // This initializes the DirectX device. It needs to be done once. // The alpha channel in the backbuffer is critical. PresentParameters presentParameters = new PresentParameters(); presentParameters.Windowed = true; presentParameters.SwapEffect = SwapEffect.Discard; presentParameters.BackBufferFormat = Format.A8R8G8B8; presentParameters.BackBufferWidth = this.Width; presentParameters.BackBufferHeight = this.Height; this.device = new Device(new Direct3D(), 0, DeviceType.Hardware, this.Handle, CreateFlags.HardwareVertexProcessing, presentParameters); Thread directx = new Thread(new ThreadStart(this.dxThread)); directx.IsBackground = true; directx.Start(); }
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 User32.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... } }
/// <summary> /// Gets a segment of the desktop as an image. /// </summary> /// <returns>A <see cref="System.Drawing.Image"/> containg an image of the full desktop.</returns> public Image GetDesktopBitmap(IntPtr hWnd) { Image capture = null; try { var crect = new User32.RECT(); User32.GetClientRect(hWnd, ref crect); var p = new User32.POINT(0, 0); User32.ClientToScreen(hWnd, ref p); crect.Top = p.Y; crect.Left = p.X; crect.Bottom = p.Y + crect.Bottom; crect.Right = p.X + crect.Right; capture = this.GetDesktopBitmap(crect); return capture; } finally { } }
internal static Point GetPosition(Visual relativeTo) { var w32Mouse = new User32.POINT(); GetCursorPos(ref w32Mouse); return relativeTo.PointFromScreen(new Point(w32Mouse.X, w32Mouse.Y)); }
private static extern bool GetCursorPos(ref User32.POINT pt);
private static extern bool ScreenToClient(IntPtr hwnd, ref User32.POINT pt);
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 User32.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... } }
/// <summary> /// Highlights the currently matched content (based /// on regex or start/end) within the richtextbox. /// </summary> private void RefreshRtfFormatting(Match match = null) { if (string.IsNullOrEmpty(rtfContent.Text) || CurrentVariable.VariableType == UrlVariable.Type.Textual) { return; } using (new ControlRedrawLock(this)) { // Determine scroll position User32.POINT scrollPos = new User32.POINT(); User32.SendMessage(rtfContent.Handle, User32.EM_GETSCROLLPOS, IntPtr.Zero, ref scrollPos); // Reset text area MatchSelection = string.Empty; m_MatchPosition = -1; rtfContent.SelectionStart = 0; rtfContent.SelectionLength = rtfContent.Text.Length; rtfContent.SelectionColor = SystemColors.WindowText; rtfContent.SelectionFont = rtfContent.Font; rtfContent.SelectionBackColor = SystemColors.Window; rtfContent.SelectionLength = 0; if (match != null) { m_MatchPosition = match.Index; rtfContent.SelectionStart = match.Index; rtfContent.SelectionLength = match.Length; rtfContent.SelectionColor = Color.White; rtfContent.SelectionBackColor = Color.Blue; if (match.Groups.Count > 1) { m_MatchPosition = match.Groups[1].Index; rtfContent.SelectionStart = match.Groups[1].Index; rtfContent.SelectionLength = match.Groups[1].Length; rtfContent.SelectionColor = Color.White; rtfContent.SelectionBackColor = Color.Red; } MatchSelection = rtfContent.SelectedText; rtfContent.SelectionLength = 0; } else if (CurrentVariable.VariableType == UrlVariable.Type.StartEnd && !string.IsNullOrEmpty(CurrentVariable.StartText)) { // Highlight StartText with blue background int pos = rtfContent.Text.IndexOf(CurrentVariable.StartText); if (pos == -1) { pos = 0; } else { rtfContent.SelectionStart = pos; rtfContent.SelectionLength = CurrentVariable.StartText.Length; rtfContent.SelectionColor = Color.White; rtfContent.SelectionBackColor = Color.Blue; } int matchStart = pos + CurrentVariable.StartText.Length; if (!string.IsNullOrEmpty(CurrentVariable.EndText) && matchStart <= rtfContent.Text.Length) { pos = rtfContent.Text.IndexOf(CurrentVariable.EndText, matchStart); if (pos >= 0) { // Highlight EndText with blue background if specified m_MatchPosition = pos; rtfContent.SelectionStart = pos; rtfContent.SelectionLength = CurrentVariable.EndText.Length; rtfContent.SelectionColor = Color.White; rtfContent.SelectionBackColor = Color.Blue; // Highlight match with red background rtfContent.SelectionStart = matchStart; rtfContent.SelectionLength = pos - matchStart; MatchSelection = rtfContent.SelectedText; rtfContent.SelectionColor = Color.White; rtfContent.SelectionBackColor = Color.Red; rtfContent.SelectionLength = 0; } } } // Restore scroll position User32.SendMessage(rtfContent.Handle, User32.EM_SETSCROLLPOS, IntPtr.Zero, ref scrollPos); } }
/// <summary> /// Highlights the currently matched content (based /// on regex or start/end) within the richtextbox. /// </summary> private void RefreshRtfFormatting(Match match) { if (string.IsNullOrEmpty(rtfContent.Text) || CurrentVariable.VariableType == UrlVariable.Type.Textual) return; using (new ControlRedrawLock(this)) { // Determine scroll position User32.POINT scrollPos = new User32.POINT(); User32.SendMessage(rtfContent.Handle, User32.EM_GETSCROLLPOS, IntPtr.Zero, ref scrollPos); // Reset text area MatchSelection = string.Empty; m_MatchPosition = -1; rtfContent.SelectionStart = 0; rtfContent.SelectionLength = rtfContent.Text.Length; rtfContent.SelectionColor = SystemColors.WindowText; rtfContent.SelectionFont = rtfContent.Font; rtfContent.SelectionBackColor = SystemColors.Window; rtfContent.SelectionLength = 0; if (match != null) { m_MatchPosition = match.Index; rtfContent.SelectionStart = match.Index; rtfContent.SelectionLength = match.Length; rtfContent.SelectionColor = Color.White; rtfContent.SelectionBackColor = Color.Blue; if (match.Groups.Count > 1) { m_MatchPosition = match.Groups[1].Index; rtfContent.SelectionStart = match.Groups[1].Index; rtfContent.SelectionLength = match.Groups[1].Length; rtfContent.SelectionColor = Color.White; rtfContent.SelectionBackColor = Color.Red; } MatchSelection = rtfContent.SelectedText; rtfContent.SelectionLength = 0; } else if (CurrentVariable.VariableType == UrlVariable.Type.StartEnd && !string.IsNullOrEmpty(CurrentVariable.StartText)) { // Highlight StartText with blue background int pos = rtfContent.Text.IndexOf(CurrentVariable.StartText); if (pos == -1) { pos = 0; } else { rtfContent.SelectionStart = pos; rtfContent.SelectionLength = CurrentVariable.StartText.Length; rtfContent.SelectionColor = Color.White; rtfContent.SelectionBackColor = Color.Blue; } int matchStart = pos + CurrentVariable.StartText.Length; if (!string.IsNullOrEmpty(CurrentVariable.EndText) && matchStart <= rtfContent.Text.Length) { pos = rtfContent.Text.IndexOf(CurrentVariable.EndText, matchStart); if (pos >= 0) { // Highlight EndText with blue background if specified m_MatchPosition = pos; rtfContent.SelectionStart = pos; rtfContent.SelectionLength = CurrentVariable.EndText.Length; rtfContent.SelectionColor = Color.White; rtfContent.SelectionBackColor = Color.Blue; // Highlight match with red background rtfContent.SelectionStart = matchStart; rtfContent.SelectionLength = pos - matchStart; MatchSelection = rtfContent.SelectedText; rtfContent.SelectionColor = Color.White; rtfContent.SelectionBackColor = Color.Red; rtfContent.SelectionLength = 0; } } } // Restore scroll position User32.SendMessage(rtfContent.Handle, User32.EM_SETSCROLLPOS, IntPtr.Zero, ref scrollPos); } }