NET programming.I have a image of a map with latitudes and longitudes on its borders .now when i drag the mouse on the map i should get a rectangle with one vertex at the mouse point and opposite one at the top left corner of map ,so that i can exactly pin pointedly locate the pixel with latitude and longitude.to be clear it should appear as a rectangle when we drag mouse on the screen.I have a code which is partially working
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
// "e.X" and "e.Y" are used to get MousePositionX and MousePositionY
rect = new Rectangle(e.X, e.Y, 0, 0);
this.Invalidate();
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
// This makes sure that the left mouse button is pressed.
if (e.Button == MouseButtons.Left)
{
// Draws the rectangle as the mouse moves
rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top);
}
this.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
using (Pen pen = new Pen(Color.Red, 2))
{
e.Graphics.DrawRectangle(pen, rect);
}
}
I don’t know where the problem exactly is but could draw a rectangle at run time.any one please help me with changes in the code.
tafa’s Answer works.
I only got two additions:
In the MouseDown Method you should
also use the following code. So
once you click somewhere in the map
you get a rectangle even when not
moving the mouse.
In the MouseMove method I would use the following code, to not create new Rectangles whenever you move the mouse: