I have a problem.
I need to add a MouseDown event to my own class (Unidad.cs) but I don't know how to do it. I have a class that extends from pictureBox and I need a MouseDown and MouseMove event to move the pictureBox, how can I do it? And... It goes always to the exact pictureBox? I mean, I will have 20 (for example) "Unidad" objects and I want to move only the Unidad object that is clicked with the mouse.
My class:
public class Unidad : PictureBox
{
//Constructor
public Unidad(string nombre, string tipo, int movimiento, int ha, int hp, int fuerza, int resistencia, int heridas, int iniciativa, int ataques, int liderazgo, int coste, string rutaImagen)
{
tipoUnidad = tipo;
movimientoUnidad = movimiento;
nombreUnidad = nombre;
costeUnidad = coste;
haUnidad = ha;
hpUnidad = hp;
fuerzaUnidad = fuerza;
resistenciaUnidad = resistencia;
iniciativaUnidad = iniciativa;
ataquesUnidad = ataques;
liderazgoUnidad = liderazgo;
object O = Resources.ResourceManager.GetObject(rutaImagen);
dibujoUnidad = new PictureBox();
dibujoUnidad.SizeMode = PictureBoxSizeMode.StretchImage;
dibujoUnidad.ClientSize = new Size(145, 67);
dibujoUnidad.Image = (Image)O;
}
//Propiedades
public string nombreUnidad { get; set; }
public string tipoUnidad { get; set; }
public int movimientoUnidad { get; set; }
public int costeUnidad { get; set; }
public int haUnidad { get; set; }
public int hpUnidad { get; set; }
public int fuerzaUnidad { get; set; }
public int resistenciaUnidad { get; set; }
public int heridasUnidad { get; set; }
public int iniciativaUnidad { get; set; }
public int ataquesUnidad { get; set; }
public int liderazgoUnidad { get; set; }
public PictureBox dibujoUnidad { get; set; }
//Método para dibujar unidad
public void Colocar(Point p, Control control, Image imagen)
{
using (Graphics g = control.CreateGraphics())
{
using (Pen pen = new Pen(Color.Red, 2))
{
g.DrawImage(imagen, p);
}
}
}
}
Thanks!
EDIT 1:
I can do it with that at the end of my "Unidad.cs":
public void Colocar(Control control, Unidad unidad, Point p)//(Point p, Control control, Image imagen)
{
control.Controls.Add(unidad);
}
protected override void OnMouseDown(MouseEventArgs e)
{
//Do Stuff here
base.OnMouseDown(e);
MessageBox.Show("HOLA");
}
The problem that I have now is that I don't have the image, I saw a black rectangle, or grey rectangle if I don't use the BackColor command, that when I click on it, it shows me a MessageBox, but I can't put the correct image or the correct location. Anyone can help me?
You are inheriting from Picturebox so you can override the Mouse events
public class Unidad : PictureBox
{
protected override void OnMouseDown(MouseEventArgs e)
{
//Do Stuff here
base.OnMouseDown(e);
}
}
I added a Panel to my form, "Form1" called "picContainer"
public Form1()
{
InitializeComponent();
picContainer.Controls.Add(new MyPictureClass()
{
Image = imageList1.Images[0],
}
);
}
I set the image from the image container.