C#检查对象是否超出界限(GUI)

时间:2015-06-20 08:44:21

标签: c#

我在C#WFA中制作一个移动的矩形。它没有问题,但它可以远离我的GUI,所以我需要检查我的矩形是否超出范围。我已经尝试过了,但它只适用于左上角。谢谢你的帮助(我的窗口是400x400)

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace Object
    {
        public partial class Form1 : Form
        {
            enum Directions { Left, Right, Up, Down }
            Directions _direct;
            private int _x;
            private int _y;

            public Form1()
            {
                InitializeComponent();
                _x = 50;
                _y = 50;
                _direct = Directions.Down;
            }

        private void Form1_Load(object sender, EventArgs e)
        {
            Invalidate();
        }

        private void form_paint(object sender, PaintEventArgs e)
        {
            e.Graphics.FillRectangle(Brushes.Black, _x, _y, 70, 70);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (_direct == Directions.Left)
            {
                _x -= 10;
                checkPosition(_x, _y);
            }
            else if (_direct == Directions.Right)
            {
                _x += 10;
                checkPosition(_x, _y);
            }
            else if (_direct == Directions.Down)
            {
                _y += 10;
                checkPosition(_x, _y);
            }
            else if (_direct == Directions.Up)
            {
                _y -= 10;
                checkPosition(_x, _y);
            }

            Invalidate();
            checkPosition(_x, _y);
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Left)
            {
                _direct = Directions.Left;
            }
            else if (e.KeyCode == Keys.Right)
            {
                _direct = Directions.Right;
            }
            else if (e.KeyCode == Keys.Up)
            {
                _direct = Directions.Up;
            }
            else if (e.KeyCode == Keys.Down)
            {
                _direct = Directions.Down;
            }
        }

        private void checkPosition(int x, int y) {
            if (x < 0) {
                _x = 0;
            }
            else if (y < 0) {
                _y = 0;
            }
            else if ((x + 70) > 400) { _x = 330; }
            else if ((y+70)>400) {_y=330;}
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果矩形和客户端矩形之间的交点是矩形,则矩形包含在客户端矩形内。使用此检查:

// rectangle is your rectangle
bool outOfBounds=!(Rectangle.Intersect(ClientRectangle, rectangle).Equals(rectangle))