Пример #1
0
        /// 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();
            }
        }
Пример #2
0
        public static async Task ClickOnPoint(IntPtr wndHandle, Point clientPoint)
        {
            User32.ClientToScreen(wndHandle, ref clientPoint);

            Cursor.Position = new Point(clientPoint.X, clientPoint.Y);
            Logger.WriteLine("Clicking " + Cursor.Position, "MouseActions", 1);

            //mouse down
            if (SystemInformation.MouseButtonsSwapped)
            {
                User32.mouse_event((uint)User32.MouseEventFlags.RightDown, 0, 0, 0, UIntPtr.Zero);
            }
            else
            {
                User32.mouse_event((uint)User32.MouseEventFlags.LeftDown, 0, 0, 0, UIntPtr.Zero);
            }

            await Task.Delay(Config.Instance.DeckExportDelay);

            //mouse up
            if (SystemInformation.MouseButtonsSwapped)
            {
                User32.mouse_event((uint)User32.MouseEventFlags.RightUp, 0, 0, 0, UIntPtr.Zero);
            }
            else
            {
                User32.mouse_event((uint)User32.MouseEventFlags.LeftUp, 0, 0, 0, UIntPtr.Zero);
            }

            await Task.Delay(Config.Instance.DeckExportDelay);
        }
        private static async Task ClickOnPoint(IntPtr wndHandle, Point clientPoint, int delay = 0)
        {
            User32.ClientToScreen(wndHandle, ref clientPoint);

            Cursor.Position = new Point(clientPoint.X, clientPoint.Y);

            //mouse down
            if (SystemInformation.MouseButtonsSwapped)
            {
                User32.mouse_event((uint)User32.MouseEventFlags.RightDown, 0, 0, 0, UIntPtr.Zero);
            }
            else
            {
                User32.mouse_event((uint)User32.MouseEventFlags.LeftDown, 0, 0, 0, UIntPtr.Zero);
            }

            await Task.Delay(delay);

            //mouse up
            if (SystemInformation.MouseButtonsSwapped)
            {
                User32.mouse_event((uint)User32.MouseEventFlags.RightUp, 0, 0, 0, UIntPtr.Zero);
            }
            else
            {
                User32.mouse_event((uint)User32.MouseEventFlags.LeftUp, 0, 0, 0, UIntPtr.Zero);
            }

            await Task.Delay(delay);
        }
Пример #4
0
        /// <summary>
        /// Captures the only the client button of a window.
        /// </summary>
        /// <param name="handle">The window handle.</param>
        /// <returns>the image of the client button.</returns>
        public static Image CaptureWindowClientArea(IntPtr handle)
        {
            // get the hDC of the target window
            IntPtr hdcSrc = User32.GetWindowDC(handle);

            // get the size
            User32.RECT windowRect = new User32.RECT();
            User32.GetWindowRect(handle, ref windowRect);


            User32.RECT windowClRect = new User32.RECT();
            User32.GetClientRect(handle, ref windowClRect);

            int top  = 0;
            int left = 0;

            System.Drawing.Point cPoint = new System.Drawing.Point();
            User32.ClientToScreen(handle, ref cPoint);
            top  = cPoint.Y - windowRect.top;
            left = cPoint.X - windowRect.left;

            int wWidth  = windowRect.right - windowRect.left;
            int wHeight = windowRect.bottom - windowRect.top;

            return(CaptureWindow(handle, windowClRect.bottom, windowClRect.right, left, top));
        }
Пример #5
0
        //get a windows absolute coordinate from an algalon coordinate
        private DrawingPoint getAbsolutePos(WindowsPoint boardPos)
        {
            DrawingPoint position = getWindowPos(boardPos);

            User32.ClientToScreen(User32.GetHearthstoneWindow(), ref position);
            return(position);
        }
Пример #6
0
        private void WebBrowserCore_OnBrowserMessage(object sender, BrowserMessageEventArgs e)
        {
            if (BrowserHandle == IntPtr.Zero)
            {
                return;
            }

            var msg = (WindowsMessages)e.BrowserMessage.Msg;

            if (CanResize && msg == WindowsMessages.WM_MOUSEMOVE)
            {
                var pt   = GetPostionFromPtr(e.BrowserMessage.LParam);
                var mode = GetSizeMode(pt);

                if (mode != HitTest.HTNOWHERE)
                {
                    User32.ClientToScreen(FormHandle, ref pt);

                    User32.PostMessage(FormHandle, (uint)WindowsMessages.WM_NCHITTEST, IntPtr.Zero, Win32.MakeParam((IntPtr)pt.x, (IntPtr)pt.y));

                    e.Handled = true;
                }
            }


            if (msg == WindowsMessages.WM_LBUTTONDOWN)
            {
                var pt       = GetPostionFromPtr(e.BrowserMessage.LParam);
                var dragable = (Chromium.DraggableRegion != null && Chromium.DraggableRegion.IsVisible(new Point(pt.x, pt.y)));

                var mode = GetSizeMode(pt);
                if (CanResize && mode != HitTest.HTNOWHERE)
                {
                    Browser.Host.NotifyMoveOrResizeStarted();

                    User32.ClientToScreen(FormHandle, ref pt);
                    User32.PostMessage(FormHandle, (uint)WindowsMessages.WM_NCLBUTTONDOWN, (IntPtr)mode, Win32.MakeParam((IntPtr)pt.x, (IntPtr)pt.y));
                    e.Handled = true;
                }
                else if (dragable && !(FormBorderStyle == FormBorderStyle.None && WindowState == FormWindowState.Maximized))
                {
                    User32.PostMessage(FormHandle, (uint)WindowsMessages.WM_USER + 1000, IntPtr.Zero, IntPtr.Zero);


                    e.Handled = true;
                }
            }

            if (CanResize && msg == WindowsMessages.WM_LBUTTONDBLCLK)
            {
                var pt       = GetPostionFromPtr(e.BrowserMessage.LParam);
                var dragable = (Chromium.DraggableRegion != null && Chromium.DraggableRegion.IsVisible(new Point(pt.x, pt.y)));
                if (dragable)
                {
                    User32.SendMessage(FormHandle, (uint)WindowsMessages.WM_NCLBUTTONDBLCLK, (IntPtr)HitTest.HTCAPTION, Win32.MakeParam((IntPtr)pt.x, (IntPtr)pt.y));
                    e.Handled = true;
                }
            }
        }
        public static Bitmap CaptureScreen(IntPtr wndHandle, Point point, int width, int height)
        {
            User32.ClientToScreen(wndHandle, ref point);
            var bmp      = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            var graphics = Graphics.FromImage(bmp);

            graphics.CopyFromScreen(point.X, point.Y, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy);
            return(bmp);
        }
Пример #8
0
        public Point GetClientOriginPoint()
        {
            POINT p = new Point(0, 0);

            User32.ClientToScreen(Handle, ref p);

            var point = new Point(p.x, p.y);

            return(point);
        }
Пример #9
0
        protected POINT MousePositionToScreen(POINT point)
        {
            POINT localPoint;

            localPoint.x = point.x;
            localPoint.y = point.y;

            User32.ClientToScreen(this.Handle, ref localPoint);

            return(localPoint);
        }
Пример #10
0
        // Token: 0x060000EF RID: 239 RVA: 0x0000816C File Offset: 0x0000636C
        public static Rectangle GetClientRectangle(IntPtr handle)
        {
            ScriptKidAntiCheat.Win32.Data.Point point;
            Rect rect;

            if (!User32.ClientToScreen(handle, out point) || !User32.GetClientRect(handle, out rect))
            {
                return(default(Rectangle));
            }
            return(new Rectangle(point.X, point.Y, rect.Right - rect.Left, rect.Bottom - rect.Top));
        }
Пример #11
0
        /// <summary>Retrieves the window's client area using the specified window handle.</summary>
        /// <param name="hWnd">A handle to the window and, indirectly, the class to which the window belongs.</param>
        /// <returns>The <see cref="Rectangle" />.</returns>
        public static Rectangle GetWindowRectangle(IntPtr hWnd)
        {
            RECT windowDimensions;

            User32.GetClientRect(hWnd, out windowDimensions);

            Point windowLocation = new Point(0, 0);

            User32.ClientToScreen(hWnd, ref windowLocation);

            return(new Rectangle(windowLocation, windowDimensions.Size));
        }
Пример #12
0
        static public KeyValuePair <UInt32[], int> Raster32BitFromClientRectFromWindowMitHandleOverDesktop(this IntPtr hWnd, bool flagCaptureblt = false)
        {
            var desktopHWnd = BotEngine.WinApi.User32.GetDesktopWindow();

            RECT clientRect;

            User32.GetClientRect(hWnd, out clientRect);

            var pointLeftTop     = clientRect.LeftTop;
            var pointRightBottom = clientRect.RightBottom;

            User32.ClientToScreen(hWnd, ref pointLeftTop);
            User32.ClientToScreen(hWnd, ref pointRightBottom);

            var windowClientRect = RectInt.FromMinPointAndMaxPoint(pointLeftTop.AsVektor2DInt(), pointRightBottom.AsVektor2DInt());

            var desktopRaster = BotEngine.Windows.Extension.Raster32BitVonClientRectVonWindowMitHandle(desktopHWnd, flagCaptureblt);

            if (desktopRaster.Key == null)
            {
                return(default(KeyValuePair <UInt32[], int>));
            }

            var desktopRasterHeight = desktopRaster.Key.Length / desktopRaster.Value;

            var destPixelCount = clientRect.Width * clientRect.Height;

            var destRaster = new UInt32[destPixelCount];

            for (int rowInDest = 0; rowInDest < clientRect.Height; rowInDest++)
            {
                var rowInDesktop = rowInDest + pointLeftTop.y;

                if (rowInDesktop < 0 || desktopRasterHeight <= rowInDesktop)
                {
                    continue;
                }

                var inRowOffsetPixelCount = Math.Max(0, -pointLeftTop.x);

                var inRowPixelCount = Math.Min(desktopRaster.Value, pointRightBottom.x) - Math.Max(0, pointLeftTop.x);

                Buffer.BlockCopy(
                    desktopRaster.Key,
                    (desktopRaster.Value * rowInDesktop + pointLeftTop.x + inRowOffsetPixelCount) * 4,
                    destRaster,
                    (clientRect.Width * rowInDest + inRowOffsetPixelCount) * 4,
                    inRowPixelCount * 4);
            }

            return(new KeyValuePair <uint[], int>(destRaster, clientRect.Width));
        }
        protected override bool GetScreenPoint(CefBrowser browser, int viewX, int viewY, ref int screenX, ref int screenY)
        {
            var scaleFactor = DpiHelper.GetScaleFactorForCurrentWindow(_owner.HostWindowHandle);


            var pt = new POINT((int)(viewX * scaleFactor), (int)(viewY * scaleFactor));

            User32.ClientToScreen(_owner.HostWindowHandle, ref pt);

            screenX = pt.x;
            screenY = pt.y;

            return(true);
        }
Пример #14
0
        public override Point PointToScreen(Point p)
        {
            var pt = new User32.POINT();

            pt.x = p.X;
            pt.y = p.Y;

            bool result = User32.ClientToScreen(Handle, ref pt);

            if (!result)
            {
                throw new Win32Exception();
            }

            return(new Point(pt.x, pt.y));
        }
Пример #15
0
        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);
        }
Пример #16
0
        private IntPtr CustomWndProc(IntPtr hWnd, uint message, IntPtr wParam, IntPtr lParam)
        {
            var msg = (WindowsMessages)message;



            if (msg == WindowsMessages.WM_LBUTTONDOWN)
            {
                var point = Win32.GetPostionFromPtr(lParam);
                User32.ClientToScreen(hWnd, ref point);

                if (User32.GetActiveWindow() != _parentHandle)
                {
                    User32.SetFocus(_parentHandle);
                }

                CastMouseDown(new Point(point.x, point.y));
            }

            if (msg == WindowsMessages.WM_SETFOCUS)
            {
                User32.SendMessage(_parentHandle, message, hWnd, IntPtr.Zero);
                UpdateZOrder();
            }

            if (msg == WindowsMessages.WM_SIZE)
            {
                int width  = Win32.SignedLOWORD(lParam);
                int height = Win32.SignedHIWORD(lParam);

                if (width != _lastUpdateWidth || height != _lastUpdateHeight)
                {
                    UpdateLayeredWindow();
                }
            }


            if (msg == WindowsMessages.WM_SETCURSOR)
            {
                SetCursor();
                return(new IntPtr(1));
            }

            return(User32.DefWindowProcW(hWnd, message, wParam, lParam));
        }
Пример #17
0
        public static System.Drawing.Rectangle GetScreenBoundingRectangle(UIElement target)
        {
            PresentationSource source = PresentationSource.FromVisual(target);

            if (source == null)
            {
                throw new InvalidOperationException("The specified UiElement is not connected to a rendering Visual Tree.");
            }

            Matrix transform;

            try
            {
                System.Windows.Media.GeneralTransform gt =
                    target.TransformToAncestor(source.RootVisual);
                System.Windows.Media.Transform t = gt as System.Windows.Media.Transform;
                if (t != null)
                {
                    transform = t.Value;
                }
                else
                {
                    throw new System.ApplicationException("//TODO: Handle GeneralTransform Case - introduced by Transforms Breaking Change");
                }
            }
            catch (InvalidOperationException)
            {
                throw new InvalidOperationException("The specified UiElement is not connected to a rendering Visual Tree.");
            }
            Rect targetRect = new Rect(new Point(), target.RenderSize);

            targetRect.Transform(transform);

            Point rootOffset = targetRect.TopLeft;

            System.Windows.Media.CompositionTarget vm = source.CompositionTarget;
            rootOffset = vm.TransformToDevice.Transform(rootOffset);//vm.DeviceUnitsFromMeasureUnits(rootOffset);
            System.Drawing.Point topLeft = new System.Drawing.Point((int)rootOffset.X, (int)rootOffset.Y);
            User32.ClientToScreen(((System.Windows.Interop.HwndSource)source).Handle, ref topLeft);

            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(topLeft, new System.Drawing.Size(Convert.ToInt32(Monitor.ConvertLogicalToScreen(Dimension.Width, target.RenderSize.Width)), Convert.ToInt32(Monitor.ConvertLogicalToScreen(Dimension.Height, target.RenderSize.Height))));

            return(rect);
        }
Пример #18
0
        public async Task ClickOnPoint(Point clientPoint)
        {
            if (!User32.IsHearthstoneInForeground() || (_onUnexpectedMousePos != null && _previousCursorPos != Point.Empty &&
                                                        (Math.Abs(_previousCursorPos.X - Cursor.Position.X) > 10 || Math.Abs(_previousCursorPos.Y - Cursor.Position.Y) > 10)))
            {
                if (!(_onUnexpectedMousePos == null || await _onUnexpectedMousePos()))
                {
                    throw new ExportingInterruptedException("Export interrupted, not continuing");
                }
                if ((_info = await ExportingHelper.EnsureHearthstoneInForeground(_info)) == null)
                {
                    throw new ExportingInterruptedException("Export interrupted - could not re-focus hearthstone");
                }
                await Task.Delay(500);
            }

            User32.ClientToScreen(_info.HsHandle, ref clientPoint);
            Cursor.Position = _previousCursorPos = new Point(clientPoint.X, clientPoint.Y);
            Log.Debug("Clicking " + Cursor.Position);

            //mouse down
            if (SystemInformation.MouseButtonsSwapped)
            {
                User32.mouse_event((uint)User32.MouseEventFlags.RightDown, 0, 0, 0, UIntPtr.Zero);
            }
            else
            {
                User32.mouse_event((uint)User32.MouseEventFlags.LeftDown, 0, 0, 0, UIntPtr.Zero);
            }

            await Task.Delay(Config.Instance.DeckExportDelay);

            //mouse up
            if (SystemInformation.MouseButtonsSwapped)
            {
                User32.mouse_event((uint)User32.MouseEventFlags.RightUp, 0, 0, 0, UIntPtr.Zero);
            }
            else
            {
                User32.mouse_event((uint)User32.MouseEventFlags.LeftUp, 0, 0, 0, UIntPtr.Zero);
            }

            await Task.Delay(Config.Instance.DeckExportDelay);
        }
Пример #19
0
        private Rectangle getAppWRect(IntPtr hWnd)
        {
            var rect = new User32.Rect();

            if (!User32.GetClientRect(new HandleRef(this, hWnd), out rect))
            {
                int ErrorCode = Marshal.GetLastWin32Error();
                MessageBox.Show("GetWindowRect returned false, error = " + ErrorCode.ToString());
            }



            if (rect.right < 0 && rect.left < 0 && rect.bottom < 0 && rect.top < 0)
            {
                Rectangle R = Rectangle.Empty;
                return(R);
            }
            else
            {
                width  = rect.right - rect.left;
                height = rect.bottom - rect.top;

                int w = width % 2;
                int h = height % 2;

                width  = width - w;
                height = height - h;

                int X = rect.left;
                int Y = rect.top;

                bool  coordinatesFound = false;
                Point point            = new Point();
                coordinatesFound = User32.ClientToScreen(hWnd, ref point);
                if (coordinatesFound)
                {
                    X = X + point.X;
                    Y = Y + point.Y;
                }

                Rectangle R = new Rectangle(X, Y, width, height);
                return(R);
            }
        }
Пример #20
0
    //private static string _assemblyShortName;

    ///// <summary>
    ///// Helper method for generating a "pack://" URI for a given relative file based on the
    ///// assembly that this class is in.
    ///// </summary>
    //public static Uri MakePackUri(string relativeFile)
    //{
    //    var uriString = "pack://application:,,,/" + AssemblyShortName + ";component/" + relativeFile;
    //    return new Uri(uriString);
    //}

    //private static string AssemblyShortName
    //{
    //    get
    //    {
    //        if (_assemblyShortName != null)
    //            return _assemblyShortName;

    //        var a = typeof(Global).Assembly;

    //        //Pull out the short name.
    //        _assemblyShortName = a.ToString().Split(',')[0];

    //        return _assemblyShortName;
    //    }
    //}

    public static Point TransformToScreen(Point point, Visual relativeTo)
    {
        var hwndSource = PresentationSource.FromVisual(relativeTo) as HwndSource;
        var root       = hwndSource.RootVisual;

        // Translate the point from the visual to the root.
        var transformToRoot = relativeTo.TransformToAncestor(root);

        var pointRoot = transformToRoot.Transform(point);

        // Transform the point from the root to client coordinates.
        var m = Matrix.Identity;

        var transform = VisualTreeHelper.GetTransform(root);

        if (transform != null)
        {
            m = Matrix.Multiply(m, transform.Value);
        }

        var offset = VisualTreeHelper.GetOffset(root);

        m.Translate(offset.X, offset.Y);

        var pointClient = m.Transform(pointRoot);

        // Convert from “device-independent pixels” into pixels.
        pointClient = hwndSource.CompositionTarget.TransformToDevice.Transform(pointClient);

        var pointClientPixels = new PointW();

        pointClientPixels.X = (0 < pointClient.X) ? (int)(pointClient.X + 0.5) : (int)(pointClient.X - 0.5);
        pointClientPixels.Y = (0 < pointClient.Y) ? (int)(pointClient.Y + 0.5) : (int)(pointClient.Y - 0.5);

        // Transform the point into screen coordinates.
        var pointScreenPixels = pointClientPixels;

        User32.ClientToScreen(hwndSource.Handle, ref pointScreenPixels);

        //Native.GetCurrentPositionEx(hwndSource.Handle, out pointScreenPixels);
        //Native.GetWindowOrgEx(hwndSource.Handle, out pointScreenPixels);

        return(new Point(pointScreenPixels.X, pointScreenPixels.Y));
    }
Пример #21
0
        /// <summary>
        /// </summary>
        public static Point GetScreenCoordinates(Point point, Visual relativeTo)
        {
            if (relativeTo == null)
            {
                throw new ArgumentNullException("relativeTo");
            }

            Visual     rootVisual = GetRootVisual(relativeTo);
            Point      point2     = relativeTo.TransformToAncestor(rootVisual).Transform(point);
            HwndSource hwndSource = GetHwndSource(relativeTo);

            if (hwndSource != null)
            {
                POINT point3 = new POINT((Int32)point2.X, (Int32)point2.Y);
                User32.ClientToScreen(hwndSource.Handle, ref point3);
                return(new Point((Double)point3.x, (Double)point3.y));
            }

            return(point2);
        }
Пример #22
0
        /// <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
            {
            }
        }
Пример #23
0
        private IntPtr GetWin32InfoFromUIElement(System.Windows.UIElement uiElement, out System.Drawing.Rectangle rect)
        {
            // Convert UIElement to Rectangle
            System.Windows.Media.Matrix       matrix;
            System.Windows.PresentationSource presentationSource = System.Windows.PresentationSource.FromVisual(uiElement);
            if (presentationSource == null)
            {
                throw new InvalidOperationException("The specified UiElement is not connected to a rendering Visual Tree.");
            }
            try
            {
                System.Windows.Media.GeneralTransform generalTransform = uiElement.TransformToAncestor(presentationSource.RootVisual);
                System.Windows.Media.Transform        transform        = generalTransform as System.Windows.Media.Transform;
                if (transform == null)
                {
                    throw new ApplicationException("//TODO: Handle GeneralTransform Case - introduced by Transforms Breaking Change");
                }
                matrix = transform.Value;
            }
            catch (InvalidOperationException)
            {
                throw new InvalidOperationException("The specified UiElement is not connected to a rendering Visual Tree.");
            }
            System.Windows.Rect rect1 = new System.Windows.Rect(new System.Windows.Point(), uiElement.RenderSize);
            rect1.Transform(matrix);
            System.Windows.Point point1 = rect1.TopLeft;
            point1 = presentationSource.CompositionTarget.TransformToDevice.Transform(point1);
            Point  point2 = new Point((int)point1.X, (int)point1.Y);
            IntPtr hwnd   = ((System.Windows.Interop.HwndSource)presentationSource).Handle; // PresentaionSource.RootVisual ?

            User32.ClientToScreen(hwnd, ref point2);
            rect = new System.Drawing.Rectangle(point2, new System.Drawing.Size(
                                                    Convert.ToInt32(Microsoft.Test.Display.Monitor.ConvertLogicalToScreen(Microsoft.Test.Display.Dimension.Width, uiElement.RenderSize.Width)),
                                                    Convert.ToInt32(Microsoft.Test.Display.Monitor.ConvertLogicalToScreen(Microsoft.Test.Display.Dimension.Height, uiElement.RenderSize.Height))));

            return(hwnd);
        }
Пример #24
0
        void UpdateMousePosition()
        {
            var io = ImGui.GetIO();

            if (io.WantSetMousePos)
            {
                var pos = new POINT((int)io.MousePos.X, (int)io.MousePos.Y);
                User32.ClientToScreen(hwnd, ref pos);
                User32.SetCursorPos(pos.X, pos.Y);
            }

            //io.MousePos = new System.Numerics.Vector2(-FLT_MAX, -FLT_MAX);

            var foregroundWindow = User32.GetForegroundWindow();

            if (foregroundWindow == hwnd || User32.IsChild(foregroundWindow, hwnd))
            {
                POINT pos;
                if (User32.GetCursorPos(out pos) && User32.ScreenToClient(hwnd, ref pos))
                {
                    io.MousePos = new System.Numerics.Vector2(pos.X, pos.Y);
                }
            }
        }
Пример #25
0
        protected POINT MousePositionToScreen(Message msg)
        {
            POINT screenPos;

            screenPos.x = (short)((uint)msg.LParam & 0x0000FFFFU);
            screenPos.y = (short)(((uint)msg.LParam & 0xFFFF0000U) >> 16);

            // Convert the mouse position to screen coordinates,
            // but not for non-client messages
            if ((msg.Msg != (int)Msgs.WM_NCLBUTTONUP) &&
                (msg.Msg != (int)Msgs.WM_NCMBUTTONUP) &&
                (msg.Msg != (int)Msgs.WM_NCRBUTTONUP) &&
                (msg.Msg != (int)Msgs.WM_NCXBUTTONUP) &&
                (msg.Msg != (int)Msgs.WM_NCLBUTTONDOWN) &&
                (msg.Msg != (int)Msgs.WM_NCMBUTTONDOWN) &&
                (msg.Msg != (int)Msgs.WM_NCRBUTTONDOWN) &&
                (msg.Msg != (int)Msgs.WM_NCXBUTTONDOWN))
            {
                // Convert the mouse position to screen coordinates
                User32.ClientToScreen(msg.HWnd, ref screenPos);
            }

            return(screenPos);
        }
Пример #26
0
        private RECT GetMaxClientRect(IntPtr hWnd)
        {
            RECT winR = default(RECT);

            User32.GetWindowRect(hWnd, ref winR);
            RECT clientR = default(RECT);

            User32.GetClientRect(hWnd, ref clientR);
            POINT point = default(POINT);

            User32.ClientToScreen(hWnd, ref point);
            Debug.WriteLine("Original win=" + winR);
            Debug.WriteLine("Original client=" + clientR);
            Debug.WriteLine("Screen pt=" + point);

            var dx = point.x - winR.left;
            var dy = point.y - winR.top;

            clientR.left   += dx;
            clientR.right  += dx;
            clientR.top    += dy;
            clientR.bottom += dy;
            return(clientR);
        }
        public async Task GetCardCounts(Deck deck)
        {
            var hsHandle = User32.GetHearthstoneWindow();

            if (!User32.IsHearthstoneInForeground())
            {
                //restore window and bring to foreground
                User32.ShowWindow(hsHandle, User32.SwRestore);
                User32.SetForegroundWindow(hsHandle);
                //wait it to actually be in foreground, else the rect might be wrong
                await Task.Delay(500);
            }
            if (!User32.IsHearthstoneInForeground())
            {
                MessageBox.Show("Can't find Hearthstone window.");
                Logger.WriteLine("Can't find Hearthstone window.", "ArenaImport");
                return;
            }
            await Task.Delay(1000);

            Core.Overlay.ForceHidden = true;
            Core.Overlay.UpdatePosition();
            const double xScale          = 0.013;
            const double yScale          = 0.017;
            const int    targetHue       = 53;
            const int    hueMargin       = 3;
            const int    numVisibleCards = 21;
            var          hsRect          = User32.GetHearthstoneRect(false);
            var          ratio           = (4.0 / 3.0) / ((double)hsRect.Width / hsRect.Height);
            var          posX            = (int)Helper.GetScaledXPos(0.92, hsRect.Width, ratio);
            var          startY          = 71.0 / 768.0 * hsRect.Height;
            var          strideY         = 29.0 / 768.0 * hsRect.Height;
            var          width           = (int)Math.Round(hsRect.Width * xScale);
            var          height          = (int)Math.Round(hsRect.Height * yScale);

            for (var i = 0; i < Math.Min(numVisibleCards, deck.Cards.Count); i++)
            {
                var posY    = (int)(startY + strideY * i);
                var capture = Helper.CaptureHearthstone(new Point(posX, posY), width, height, hsHandle);
                if (capture == null)
                {
                    continue;
                }
                var yellowPixels = 0;
                for (var x = 0; x < width; x++)
                {
                    for (var y = 0; y < height; y++)
                    {
                        var pixel = capture.GetPixel(x, y);
                        if (Math.Abs(pixel.GetHue() - targetHue) < hueMargin)
                        {
                            yellowPixels++;
                        }
                    }
                }
                //Console.WriteLine(yellowPixels + " of " + width * height + " - " + yellowPixels / (double)(width * height));
                //capture.Save("arenadeckimages/" + i + ".png");
                var yellowPixelRatio = yellowPixels / (double)(width * height);
                if (yellowPixelRatio > 0.25 && yellowPixelRatio < 50)
                {
                    deck.Cards[i].Count = 2;
                }
            }

            if (deck.Cards.Count > numVisibleCards)
            {
                const int scrollClicksPerCard = 4;
                const int scrollDistance      = 120;
                var       clientPoint         = new Point(posX, (int)startY);
                var       previousPos         = System.Windows.Forms.Cursor.Position;
                User32.ClientToScreen(hsHandle, ref clientPoint);
                System.Windows.Forms.Cursor.Position = new Point(clientPoint.X, clientPoint.Y);
                for (var j = 0; j < scrollClicksPerCard * (deck.Cards.Count - numVisibleCards); j++)
                {
                    User32.mouse_event((uint)User32.MouseEventFlags.Wheel, 0, 0, -scrollDistance, UIntPtr.Zero);
                    await Task.Delay(30);
                }
                System.Windows.Forms.Cursor.Position = previousPos;
                await Task.Delay(100);

                var remainingCards = deck.Cards.Count - numVisibleCards;
                startY = 76.0 / 768.0 * hsRect.Height + (numVisibleCards - remainingCards) * strideY;
                for (var i = 0; i < remainingCards; i++)
                {
                    var posY    = (int)(startY + strideY * i);
                    var capture = Helper.CaptureHearthstone(new Point(posX, posY), width, height, hsHandle);
                    if (capture == null)
                    {
                        continue;
                    }
                    var yellowPixels = 0;
                    for (var x = 0; x < width; x++)
                    {
                        for (var y = 0; y < height; y++)
                        {
                            var pixel = capture.GetPixel(x, y);
                            if (Math.Abs(pixel.GetHue() - targetHue) < hueMargin)
                            {
                                yellowPixels++;
                            }
                        }
                    }
                    var yellowPixelRatio = yellowPixels / (double)(width * height);
                    if (yellowPixelRatio > 0.25 && yellowPixelRatio < 50)
                    {
                        deck.Cards[numVisibleCards + i].Count = 2;
                    }
                }

                System.Windows.Forms.Cursor.Position = new Point(clientPoint.X, clientPoint.Y);
                for (var j = 0; j < scrollClicksPerCard * (deck.Cards.Count - 21); j++)
                {
                    User32.mouse_event((uint)User32.MouseEventFlags.Wheel, 0, 0, scrollDistance, UIntPtr.Zero);
                    await Task.Delay(30);
                }
                System.Windows.Forms.Cursor.Position = previousPos;
            }

            Core.Overlay.ForceHidden = false;
            Core.Overlay.UpdatePosition();

            ActivateWindow();
        }
Пример #28
0
        /// <summary>
        ///  This method will either initiate a new resize operation or continue with an existing one.  If we're currently dragging (i.e. resizing) then we look at the resize rules and set the bounds of each control to the new location of the mouse pointer.
        /// </summary>
        public override bool OnMouseMove(Glyph g, MouseButtons button, Point mouseLoc)
        {
            if (!_pushedBehavior)
            {
                return(false);
            }

            bool altKeyPressed = Control.ModifierKeys == Keys.Alt;

            if (altKeyPressed && _dragManager != null)
            {
                //erase any snaplines (if we had any)
                _dragManager.EraseSnapLines();
            }

            if (!altKeyPressed && mouseLoc.Equals(_lastMouseLoc))
            {
                return(true);
            }

            // When DesignerWindowPane has scrollbars and we resize, shrinking the the DesignerWindowPane makes it look like the mouse has moved to the BS.  To compensate for that we keep track of the mouse's previous position in screen coordinates, and use that to compare if the mouse has really moved.
            if (_lastMouseAbs != null)
            {
                var mouseLocAbs = new Point(mouseLoc.X, mouseLoc.Y);
                User32.ClientToScreen(new HandleRef(this, _behaviorService.AdornerWindowControl.Handle), ref mouseLocAbs);
                if (mouseLocAbs.X == _lastMouseAbs.X && mouseLocAbs.Y == _lastMouseAbs.Y)
                {
                    return(true);
                }
            }

            if (!_dragging)
            {
                if (Math.Abs(_initialPoint.X - mouseLoc.X) > DesignerUtils.MinDragSize.Width / 2 || Math.Abs(_initialPoint.Y - mouseLoc.Y) > DesignerUtils.MinDragSize.Height / 2)
                {
                    InitiateResize();
                    _dragging = true;
                }
                else
                {
                    return(false);
                }
            }

            if (_resizeComponents is null || _resizeComponents.Length == 0)
            {
                return(false);
            }
            // we do these separately so as not to disturb the cached sizes for values we're not actually changing.  For example, if a control is docked top and we modify the height, the width shouldn't be modified.
            PropertyDescriptor propWidth  = null;
            PropertyDescriptor propHeight = null;
            PropertyDescriptor propTop    = null;
            PropertyDescriptor propLeft   = null;

            // We do this to make sure that Undo works correctly.
            if (_initialResize)
            {
                propWidth  = TypeDescriptor.GetProperties(_resizeComponents[0].resizeControl)["Width"];
                propHeight = TypeDescriptor.GetProperties(_resizeComponents[0].resizeControl)["Height"];
                propTop    = TypeDescriptor.GetProperties(_resizeComponents[0].resizeControl)["Top"];
                propLeft   = TypeDescriptor.GetProperties(_resizeComponents[0].resizeControl)["Left"];

                // validate each of the property descriptors.
                if (propWidth != null && !typeof(int).IsAssignableFrom(propWidth.PropertyType))
                {
                    propWidth = null;
                }

                if (propHeight != null && !typeof(int).IsAssignableFrom(propHeight.PropertyType))
                {
                    propHeight = null;
                }

                if (propTop != null && !typeof(int).IsAssignableFrom(propTop.PropertyType))
                {
                    propTop = null;
                }

                if (propLeft != null && !typeof(int).IsAssignableFrom(propLeft.PropertyType))
                {
                    propLeft = null;
                }
            }

            Control targetControl = _resizeComponents[0].resizeControl as Control;

            _lastMouseLoc = mouseLoc;
            _lastMouseAbs = new Point(mouseLoc.X, mouseLoc.Y);
            User32.ClientToScreen(new HandleRef(this, _behaviorService.AdornerWindowControl.Handle), ref _lastMouseAbs);
            int minHeight = Math.Max(targetControl.MinimumSize.Height, MINSIZE);
            int minWidth  = Math.Max(targetControl.MinimumSize.Width, MINSIZE);

            if (_dragManager != null)
            {
                bool shouldSnap             = true;
                bool shouldSnapHorizontally = true;
                //if the targetcontrol is at min-size then we do not want to offer up snaplines
                if ((((_targetResizeRules & SelectionRules.BottomSizeable) != 0) || ((_targetResizeRules & SelectionRules.TopSizeable) != 0)) &&
                    (targetControl.Height == minHeight))
                {
                    shouldSnap = false;
                }
                else if ((((_targetResizeRules & SelectionRules.RightSizeable) != 0) || ((_targetResizeRules & SelectionRules.LeftSizeable) != 0)) &&
                         (targetControl.Width == minWidth))
                {
                    shouldSnap = false;
                }

                //if the targetControl has IntegralHeight turned on, then don't snap if the control can be resized vertically
                PropertyDescriptor propIntegralHeight = TypeDescriptor.GetProperties(targetControl)["IntegralHeight"];
                if (propIntegralHeight != null)
                {
                    object value = propIntegralHeight.GetValue(targetControl);
                    if (value is bool && (bool)value == true)
                    {
                        shouldSnapHorizontally = false;
                    }
                }

                if (!altKeyPressed && shouldSnap)
                {
                    //here, ask the snapline engine to suggest an offset during our resize
                    // Remembering the last snapoffset allows us to correctly erase snaplines, if the user subsequently holds down the Alt-Key. Remember that we don't physically move the mouse, we move the control. So if we didn't remember the last snapoffset and the user then hit the Alt-Key, we would actually redraw the control at the actual mouse location, which would make the control "jump" which is not what the user would expect. Why does the control "jump"? Because when a control is snapped, we have offset the control relative to where the mouse is, but we have not update the physical mouse position.
                    // When the user hits the Alt-Key they expect the control to be where it was (whether snapped or not). we can't rely on lastSnapOffset to check whether we snapped. We used to check if it was empty, but it can be empty and we still snapped (say the control was snapped, as you continue to move the mouse, it will stay snapped for a while. During that while the snapoffset will got from x to -x (or vice versa) and a one point hit 0.
                    // Since we have to calculate the new size/location differently based on whether we snapped or not, we have to know for sure if we snapped. We do different math because of bug 264996:
                    //  - if you snap, we want to move the control edge.
                    //  - otherwise, we just want to change the size by the number of pixels moved.
                    _lastSnapOffset = _dragManager.OnMouseMove(targetControl, GenerateSnapLines(_targetResizeRules, mouseLoc), ref _didSnap, shouldSnapHorizontally);
                }
                else
                {
                    _dragManager.OnMouseMove(new Rectangle(-100, -100, 0, 0)); /*just an invalid rect - so we won't snap*///);
                }

                // If there's a line to snap to, the offset will come back non-zero. In that case we should adjust the mouse position with the offset such that the size calculation below takes that offset into account. If there's no line, then the offset is 0, and there's no harm in adding the offset.
                mouseLoc.X += _lastSnapOffset.X;
                mouseLoc.Y += _lastSnapOffset.Y;
            }

            // IF WE ARE SNAPPING TO A CONTROL, then we also need to adjust for the offset between the initialPoint (where the MouseDown happened) and the edge of the control otherwise we would be those pixels off when resizing the control. Remember that snaplines are based on the targetControl, so we need to use the targetControl to figure out the offset.
            Rectangle controlBounds = new Rectangle(_resizeComponents[0].resizeBounds.X, _resizeComponents[0].resizeBounds.Y,
                                                    _resizeComponents[0].resizeBounds.Width, _resizeComponents[0].resizeBounds.Height);

            if ((_didSnap) && (targetControl.Parent != null))
            {
                controlBounds.Location = _behaviorService.MapAdornerWindowPoint(targetControl.Parent.Handle, controlBounds.Location);
                if (targetControl.Parent.IsMirrored)
                {
                    controlBounds.Offset(-controlBounds.Width, 0);
                }
            }

            Rectangle newBorderRect    = Rectangle.Empty;
            Rectangle targetBorderRect = Rectangle.Empty;
            bool      drawSnapline     = true;
            Color     backColor        = targetControl.Parent != null ? targetControl.Parent.BackColor : Color.Empty;

            for (int i = 0; i < _resizeComponents.Length; i++)
            {
                Control   control   = _resizeComponents[i].resizeControl as Control;
                Rectangle bounds    = control.Bounds;
                Rectangle oldBounds = bounds;
                // We need to compute the offset beased on the original cached Bounds ... ListBox doesnt allow drag on the top boundary if this is not done when it is "IntegralHeight"
                Rectangle baseBounds    = _resizeComponents[i].resizeBounds;
                Rectangle oldBorderRect = BehaviorService.ControlRectInAdornerWindow(control);
                bool      needToUpdate  = true;
                // The ResizeBehavior can easily get into a situation where we are fighting with a layout engine. E.g., We resize control to 50px, LayoutEngine lays out and finds 50px was too small and resized back to 100px.  This is what should happen, but it looks bad in the designer.  To avoid the flicker we temporarily turn off painting while we do the resize.
                User32.SendMessageW(control, User32.WM.SETREDRAW, PARAM.FromBool(false));
                try
                {
                    bool fRTL = false;
                    // If the container is mirrored the control origin is in upper-right, so we need to adjust our math for that. Remember that mouse coords have origin in upper left.
                    if (control.Parent != null && control.Parent.IsMirrored)
                    {
                        fRTL = true;
                    }
                    // figure out which ones we're actually changing so we don't blow away the controls cached sizing state.  This is important if things are docked we don't want to destroy their "pre-dock" size.
                    BoundsSpecified specified = BoundsSpecified.None;
                    // When we check if we should change height, width, location,  we first have to check if the targetControl allows resizing, and then if the control we are currently resizing allows it as well.
                    SelectionRules resizeRules = _resizeComponents[i].resizeRules;
                    if (((_targetResizeRules & SelectionRules.BottomSizeable) != 0) &&
                        ((resizeRules & SelectionRules.BottomSizeable) != 0))
                    {
                        int pixelHeight;
                        if (_didSnap)
                        {
                            pixelHeight = mouseLoc.Y - controlBounds.Bottom;
                        }
                        else
                        {
                            pixelHeight = AdjustPixelsForIntegralHeight(control, mouseLoc.Y - _initialPoint.Y);
                        }

                        bounds.Height = Math.Max(minHeight, baseBounds.Height + pixelHeight);
                        specified    |= BoundsSpecified.Height;
                    }

                    if (((_targetResizeRules & SelectionRules.TopSizeable) != 0) &&
                        ((resizeRules & SelectionRules.TopSizeable) != 0))
                    {
                        int yOffset;
                        if (_didSnap)
                        {
                            yOffset = controlBounds.Y - mouseLoc.Y;
                        }
                        else
                        {
                            yOffset = AdjustPixelsForIntegralHeight(control, _initialPoint.Y - mouseLoc.Y);
                        }

                        specified    |= BoundsSpecified.Height;
                        bounds.Height = Math.Max(minHeight, baseBounds.Height + yOffset);
                        if ((bounds.Height != minHeight) ||
                            ((bounds.Height == minHeight) && (oldBounds.Height != minHeight)))
                        {
                            specified |= BoundsSpecified.Y;
                            //if you do it fast enough, we actually could end up placing the control off the parent (say off the form), so enforce a "minimum" location
                            bounds.Y = Math.Min(baseBounds.Bottom - minHeight, baseBounds.Y - yOffset);
                        }
                    }

                    if (((((_targetResizeRules & SelectionRules.RightSizeable) != 0) && ((resizeRules & SelectionRules.RightSizeable) != 0)) && (!fRTL)) ||
                        ((((_targetResizeRules & SelectionRules.LeftSizeable) != 0) && ((resizeRules & SelectionRules.LeftSizeable) != 0)) && (fRTL)))
                    {
                        specified |= BoundsSpecified.Width;
                        int xOffset = _initialPoint.X;
                        if (_didSnap)
                        {
                            xOffset = !fRTL ? controlBounds.Right : controlBounds.Left;
                        }
                        bounds.Width = Math.Max(minWidth, baseBounds.Width + (!fRTL ? (mouseLoc.X - xOffset) : (xOffset - mouseLoc.X)));
                    }

                    if (((((_targetResizeRules & SelectionRules.RightSizeable) != 0) && ((resizeRules & SelectionRules.RightSizeable) != 0)) && (fRTL)) ||
                        ((((_targetResizeRules & SelectionRules.LeftSizeable) != 0) && ((resizeRules & SelectionRules.LeftSizeable) != 0)) && (!fRTL)))
                    {
                        specified |= BoundsSpecified.Width;
                        int xPos = _initialPoint.X;
                        if (_didSnap)
                        {
                            xPos = !fRTL ? controlBounds.Left : controlBounds.Right;
                        }

                        int xOffset = !fRTL ? (xPos - mouseLoc.X) : (mouseLoc.X - xPos);
                        bounds.Width = Math.Max(minWidth, baseBounds.Width + xOffset);
                        if ((bounds.Width != minWidth) ||
                            ((bounds.Width == minWidth) && (oldBounds.Width != minWidth)))
                        {
                            specified |= BoundsSpecified.X;
                            //if you do it fast enough, we actually could end up placing the control off the parent (say off the form), so enforce a "minimum" location
                            bounds.X = Math.Min(baseBounds.Right - minWidth, baseBounds.X - xOffset);
                        }
                    }

                    if (!_parentGridSize.IsEmpty)
                    {
                        bounds = AdjustToGrid(bounds, _targetResizeRules);
                    }

                    // Checking specified (check the diff) rather than bounds.<foo> != resizeBounds[i].<foo> also handles the following corner cases:
                    // 1. Create a form and add 2 buttons. Make sure that they are snapped to the left edge. Now grab the left edge of button 1, and start resizing to the left, past the snapline you will initially get, and then back to the right. What you would expect is to get the left edge snapline again. But without the specified check you wouldn't. This is because the bounds.<foo> != resizeBounds[i].<foo> checks would fail, since the new size would now be the original size. We could probably live with that, except that we draw the snapline below, since we correctly identified one. We could hack it so that we didn't draw the snapline, but that would confuse the user even more.
                    // 2. Create a form and add a single button. Place it at 100,100. Now start resizing it to the left and then back to the right. Note that with the original check (see diff), you would never be able to resize it back to position 100,100. You would get to 99,100 and then to 101,100.
                    if (((specified & BoundsSpecified.Width) == BoundsSpecified.Width) &&
                        _dragging && _initialResize && propWidth != null)
                    {
                        propWidth.SetValue(_resizeComponents[i].resizeControl, bounds.Width);
                    }

                    if (((specified & BoundsSpecified.Height) == BoundsSpecified.Height) &&
                        _dragging && _initialResize && propHeight != null)
                    {
                        propHeight.SetValue(_resizeComponents[i].resizeControl, bounds.Height);
                    }

                    if (((specified & BoundsSpecified.X) == BoundsSpecified.X) &&
                        _dragging && _initialResize && propLeft != null)
                    {
                        propLeft.SetValue(_resizeComponents[i].resizeControl, bounds.X);
                    }

                    if (((specified & BoundsSpecified.Y) == BoundsSpecified.Y) &&
                        _dragging && _initialResize && propTop != null)
                    {
                        propTop.SetValue(_resizeComponents[i].resizeControl, bounds.Y);
                    }

                    // We check the dragging bit here at every turn, because if there was a popup we may have lost capture and we are terminated.  At that point we shouldn't make any changes.
                    if (_dragging)
                    {
                        control.SetBounds(bounds.X, bounds.Y, bounds.Width, bounds.Height, specified);
                        //Get the new resize border
                        newBorderRect = BehaviorService.ControlRectInAdornerWindow(control);
                        if (control.Equals(targetControl))
                        {
                            Debug.Assert(i == 0, "The first control in the Selection should be the target control");
                            targetBorderRect = newBorderRect;
                        }

                        //Check that the control really did resize itself. Some controls (like ListBox, MonthCalendar) might adjust to a slightly different size than the one we pass in SetBounds. If if didn't size, then there's no need to invalidate anything
                        if (control.Bounds == oldBounds)
                        {
                            needToUpdate = false;
                        }
                        // We would expect the bounds now to be what we set it to above, but this might not be the case. If the control is hosted with e.g. a FLP, then setting the bounds above actually might force a re-layout, and the control will get moved to another spot. In this case, we don't really want to draw a snapline. Even if we snapped to a snapline, if the control got moved, the snapline would be in the wrong place.
                        if (control.Bounds != bounds)
                        {
                            drawSnapline = false;
                        }
                    }

                    if (control == _primaryControl && _statusCommandUI != null)
                    {
                        _statusCommandUI.SetStatusInformation(control as Component);
                    }
                }
                finally
                {
                    // While we were resizing we discarded painting messages to reduce flicker.  We now turn painting back on and manually refresh the controls.
                    User32.SendMessageW(control, User32.WM.SETREDRAW, PARAM.FromBool(true));
                    //update the control
                    if (needToUpdate)
                    {
                        Control parent = control.Parent;
                        if (parent != null)
                        {
                            control.Invalidate(/* invalidateChildren = */ true);
                            parent.Invalidate(oldBounds, /* invalidateChildren = */ true);
                            parent.Update();
                        }
                        else
                        {
                            control.Refresh();
                        }
                    }

                    //render the resize border
                    if (!newBorderRect.IsEmpty)
                    {
                        using (Region newRegion = new Region(newBorderRect))
                        {
                            newRegion.Exclude(Rectangle.Inflate(newBorderRect, -BorderSize, -BorderSize));
                            //No reason to get smart about only invalidating part of the border. Thought we could be but no.The reason is the order: ... the new border is drawn (last resize) On next mousemove, the control is resized which redraws the control AND ERASES THE BORDER Then we draw the new border - flash baby.                            Thus this will always flicker.
                            if (needToUpdate)
                            {
                                using (Region oldRegion = new Region(oldBorderRect))
                                {
                                    oldRegion.Exclude(Rectangle.Inflate(oldBorderRect, -BorderSize, -BorderSize));
                                    BehaviorService.Invalidate(oldRegion);
                                }
                            }

                            //draw the new border captureLost could be true if a popup came up and caused a lose focus
                            if (!_captureLost)
                            {
                                using (Graphics graphics = BehaviorService.AdornerWindowGraphics)
                                {
                                    if (_lastResizeRegion != null)
                                    {
                                        if (!_lastResizeRegion.Equals(newRegion, graphics))
                                        {
                                            _lastResizeRegion.Exclude(newRegion);          //we don't want to invalidate this region.
                                            BehaviorService.Invalidate(_lastResizeRegion); //might be the same, might not.
                                            _lastResizeRegion.Dispose();
                                            _lastResizeRegion = null;
                                        }
                                    }
                                    DesignerUtils.DrawResizeBorder(graphics, newRegion, backColor);
                                }
                                if (_lastResizeRegion is null)
                                {
                                    _lastResizeRegion = newRegion.Clone(); //we will need to dispose it later.
                                }
                            }
                        }
                    }
                }
            }

            if ((drawSnapline) && (!altKeyPressed) && (_dragManager != null))
            {
                _dragManager.RenderSnapLinesInternal(targetBorderRect);
            }

            _initialResize = false;
            return(true);
        }
 /// <summary>
 /// Get window client rectangle.
 /// </summary>
 public static System.Drawing.Rectangle GetClientRectangle(IntPtr handle)
 {
     return(User32.ClientToScreen(handle, out var point) && User32.GetClientRect(handle, out var rect)
         ? new System.Drawing.Rectangle(point.X, point.Y, rect.Right - rect.Left, rect.Bottom - rect.Top)
         : default);
Пример #30
0
        private ErrorCode CopyGdiScreenToDxSurf()
        {
            ErrorCode errorCode = ErrorCode.Unexpected;

            try
            {
                if (hWnd != IntPtr.Zero)
                {
                    var isIconic = User32.IsIconic(hWnd);
                    if (!isIconic)
                    {
                        var clientRect = User32.GetClientRect(hWnd);

                        if (this.SrcRect != clientRect)
                        {
                            logger.Info(SrcRect.ToString());

                            this.SrcRect = clientRect;

                            if (gdiTexture != null)
                            {
                                gdiTexture.Dispose();
                                gdiTexture = null;
                            }
                        }
                    }
                    else
                    {
                        logger.Debug("IsIconic: " + hWnd);
                        return(ErrorCode.Ok);
                    }

                    var srcWidth  = SrcRect.Width;
                    var srcHeight = SrcRect.Height;

                    if (srcWidth == 0 || srcHeight == 0)
                    {
                        logger.Error("Invalid rect: " + SrcRect.ToString());
                        return(ErrorCode.Unexpected);
                    }

                    if (gdiTexture == null)
                    {
                        gdiTexture = new Texture2D(device,
                                                   new Texture2DDescription
                        {
                            CpuAccessFlags    = CpuAccessFlags.None,
                            BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                            Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                            Width             = SrcRect.Width,
                            Height            = SrcRect.Height,
                            MipLevels         = 1,
                            ArraySize         = 1,
                            SampleDescription = { Count = 1, Quality = 0 },
                            Usage             = ResourceUsage.Default,
                            OptionFlags       = ResourceOptionFlags.GdiCompatible,
                        });
                    }
                }



                using (var surf = gdiTexture.QueryInterface <SharpDX.DXGI.Surface1>())
                {
                    int nXSrc      = SrcRect.Left;
                    int nYSrc      = SrcRect.Top;
                    int nWidthSrc  = SrcRect.Width;
                    int nHeightSrc = SrcRect.Height;

                    var descr = surf.Description;

                    int nXDest  = 0;
                    int nYDest  = 0;
                    int nWidth  = descr.Width;
                    int nHeight = descr.Height;

                    try
                    {
                        var    hdcDest = surf.GetDC(true);
                        IntPtr hdcSrc  = IntPtr.Zero;
                        try
                        {
                            hdcSrc = User32.GetDC(hWnd);
                            //hdcSrc = User32.GetDC(IntPtr.Zero);
                            //hdcSrc = User32.GetWindowDC(hWnd);

                            var dwRop = TernaryRasterOperations.SRCCOPY;
                            if (CaptureAllLayers)
                            {
                                dwRop |= TernaryRasterOperations.CAPTUREBLT;
                            }

                            //var dwRop = TernaryRasterOperations.CAPTUREBLT | TernaryRasterOperations.SRCCOPY;
                            //var dwRop = TernaryRasterOperations.SRCCOPY;

                            //bool success = User32.PrintWindow(hWnd, hdcDest, 0);

                            bool success = Gdi32.BitBlt(hdcDest, nXDest, nYDest, nWidth, nHeight, hdcSrc, nXSrc, nYSrc, dwRop);
                            if (!success)
                            {
                                throw new Win32Exception(Marshal.GetLastWin32Error());
                            }

                            if (CaptureMouse)
                            {
                                var x = nXSrc;
                                var y = nYSrc;

                                if (hWnd != IntPtr.Zero)
                                {
                                    POINT lpPoint = new POINT
                                    {
                                        x = 0,
                                        y = 0,
                                    };

                                    User32.ClientToScreen(hWnd, ref lpPoint);

                                    x = lpPoint.x;
                                    y = lpPoint.y;
                                }

                                User32.DrawCursorEx(hdcDest, x, y);
                            }

                            errorCode = ErrorCode.Ok;
                        }
                        finally
                        {
                            Gdi32.DeleteDC(hdcSrc);
                        }
                    }
                    catch (Win32Exception ex)
                    {
                        logger.Warn(ex);

                        if (ex.NativeErrorCode == Win32ErrorCodes.ERROR_ACCESS_DENIED ||
                            ex.NativeErrorCode == Win32ErrorCodes.ERROR_INVALID_HANDLE)
                        {
                            errorCode = ErrorCode.AccessDenied;
                        }
                    }
                    finally
                    {
                        surf.ReleaseDC();
                    }
                }

                if (errorCode == ErrorCode.Ok)
                {
                    Texture2D finalTexture = gdiTexture;
                    if (renderTarget != null)
                    {                                            // масштабируем текстуру если нужно
                        renderTarget.BeginDraw();
                        renderTarget.Clear(SharpDX.Color.Black); //(Color.Red);

                        DrawTexture(renderTarget, gdiTexture);

                        renderTarget.EndDraw();
                        finalTexture = renderTexture;
                    }

                    //device.ImmediateContext.CopySubresourceRegion(finalTexture, SharedTexture);

                    device.ImmediateContext.CopyResource(finalTexture, SharedTexture);
                    device.ImmediateContext.Flush();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(errorCode);
        }