Search code examples
c#winformswindowrectangles

c# - Get Rectangle of Form


I'm working on a car-animation in C# and want to test if the car is still in the Window. I created a form with the Windows-Forms Designer.

I have a Rectangle of the Car:

public Rectangle CarShape { get; set; }
...
CarShape = new Rectangle(Pos, new Size(28, 62));

And my Form1 Class:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Startcars();
    }
    //Here is my Question:
    public static Rectangle Window { get; } = new Rectangle(new Point(0,0),Form1.Size);
...
}

Here I get the Error: "An object reference is required for the non-static field, method, or property 'Form.Size'".

I also tried it with 'this', which appears to be also invalid in a static property. If I change the Property to non static, this gets invalid in the current context.

Later I'm going to check it with if(!Window.Contains(car.CarShape))

How can I get the Window as a rectangle or is there a better way of testing if the car is still inside the window?


Solution

  • The problem must be trying to initialize your varible in the definition. Do this:

    1- Declare the variable as:

    public Rectangle win { get; } 
    

    2- Then in the form's constructor:

    public Form1()
    {
        InitializeComponent();
        Startcars();
        win = new Rectangle(new Point(0, 0), this.Size);
    }
    

    As @Lithium says in a comment, you shouldn't name Window to the variable, as it can be confusing. It's always a good idea to follow the Naming Conventions in C#

    Edit

    You should also be using this.ClientRectangle instead of this.Size (thanks Reza Aghaei for pointing it out.