Imrik
Imrik

Reputation: 664

DrawRectangle doesn't work

I have a rectangle on a class created by me. The function "DrawRectangle" doesn't draw anything. I put the code below:

My own class (Unidad.cs):

class Unidad
{
    //Constructor
    public Unidad(string tipo, int movimiento)
    {
        tipoUnidad = tipo;
        movimientoUnidad = movimiento;
    }

    //Propiedades
    public string tipoUnidad {get; set;}
    public int movimientoUnidad { get; set; }

    //Método para dibujar unidad
    public void colocar(MouseEventArgs e)
    {            
        Form1 myf = new Form1();

        using (Graphics g = myf.picboxFondo.CreateGraphics())
        {
            Pen pen = new Pen(Color.Red, 2);

            g.DrawRectangle(pen, e.X, e.Y, 20, 20);

            pen.Dispose();
            g.Dispose();
        }
    }
}

Main class:

public partial class Form1 : Form
{
    //Prueba de clase
    Unidad prueba;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        picboxFondo.Size = ClientRectangle.Size;
        prueba = new Unidad("I", 20);
    }

    private void picboxFondo_MouseDown(object sender, MouseEventArgs e)
    {
        prueba.colocar(e);
    }
}

I have picboxFondo Modifiers public. All compile correctly and works perfect, but when I go to g.DrawRectangle I see all the values are OK but it doesn't draw anything.

Can you help me?

Thanks!

Upvotes: 0

Views: 990

Answers (1)

René Vogt
René Vogt

Reputation: 43876

You are creating a new instance of your Form1 class and try to draw on the PictureBox of that new instance (which isn't shown at all).

Instead you can pass the control you want to draw on as a parameter to your colocar method:

public void colocar(Point p, Control control)
{
    using (Graphics g = control.CreateGraphics())
    {
        using (Pen pen = new Pen(Color.Red, 2))
        {
            g.DrawRectangle(pen, p.X, p.Y, 20, 20);
        }
    }
}

and call it like that in your form:

private void picboxFondo_MouseDown(object sender, MouseEventArgs e)
{
    prueba.colocar(e.Location, picboxFondo);
}

I also changed the method so that you only pass the Location of the MouseEventArgs, because your drawing method doesn't need to know anything about mouse events, only about the Point.
And note that there is no need to call Dispose on the Pen or the Graphics, the using statement is doing that for you.
And you may consider using the .NET naming conventions and rename your method Colocar.

Upvotes: 4

Related Questions