如何在Windows窗体上获取PictureBox的左上角屏幕坐标

时间:2011-12-17 16:19:12

标签: c# .net winforms coordinates picturebox

我的Windows窗体上有一个PictureBox

我正在使用RectanglePictureBox上绘制ControlPaint.DrawReversibleFrame(),并希望对某些边界进行编码,因此我只使用PictureBox而不是整个屏幕。

如何找到PictureBox

的topleft点的屏幕坐标

使用解决方案编辑:这是我的解决方案,如果有人需要编写一些PictureBox边界。

                if (_isDragging) // If the mouse is being dragged, undraw and redraw the rectangle as the mouse moves.
                {
                    pictureBoxMap.Refresh();
                    ControlPaint.DrawReversibleFrame(_theRectangleScreenCoords, BackColor, FrameStyle.Dashed); // Hide the previous rectangle by calling the DrawReversibleFrame method with the same parameters.

                    Point endPoint = ((Control)sender).PointToScreen(new Point(e.X, e.Y));
                    var topLeftPictureBoxMap = pictureBoxMap.PointToScreen(new Point(0, 0));
                    int width = endPoint.X - _startPointTheRectangleScreenCoords.X;
                    int height = endPoint.Y - _startPointTheRectangleScreenCoords.Y;

                    // limit rectangle in x-axis
                    var diff_x = pictureBoxMap.Width - (_startPointTheRectangleScreenCoords.X - topLeftPictureBoxMap.X);
                    var diff_x_2 = (pictureBoxMap.Width - (_startPointTheRectangleScreenCoords.X - topLeftPictureBoxMap.X)) - pictureBoxMap.Width;
                    if (width > diff_x)
                    {
                        width = diff_x;
                    }
                    else if(width < diff_x_2)
                    {
                        width = diff_x_2;
                    }

                    // limit rectangle i y-aksen
                    var diff_Y = pictureBoxMap.Height - (_startPointTheRectangleScreenCoords.Y - topLeftPictureBoxMap.Y);
                    var diff_Y_2 = (pictureBoxMap.Height - (_startPointTheRectangleScreenCoords.Y - topLeftPictureBoxMap.Y)) - pictureBoxMap.Height;

                    if (height > diff_Y)
                    {
                        height = diff_Y;
                    }
                    else if(height < diff_Y_2)
                    {
                        height = diff_Y_2;
                    }

                    _theRectangleScreenCoords = new Rectangle(
                        _startPointTheRectangleScreenCoords.X,
                        _startPointTheRectangleScreenCoords.Y,
                        width,
                        height);

                    ControlPaint.DrawReversibleFrame(_theRectangleScreenCoords, Color.Red, FrameStyle.Dashed); // Draw the new rectangle by calling DrawReversibleFrame again.
                }

1 个答案:

答案 0 :(得分:4)

使用Control.PointToScreen( new Point(0, 0) ),其中Control是您的PictureBox。 见http://msdn.microsoft.com/en-us/library/system.windows.forms.control.pointtoscreen.aspx