Я пытаюсь переместить и изменить размер нарисованного прямоугольника, используя события мыши, вычисляется новое начальное местоположение x, y, но положение прямоугольника не обновляется: исходный код моей формы:
public partial class Form3 : Form
{
Rectangle rect;
Point StartXY;
Point EndXY;
int x = 0;
int y = 0;
int height = 0;
int width = 0;
bool m_mouseDown = false;
bool m_movingRect = false;
Pen rectPen = new Pen(Color.Red, 1);
public Form3()
{
InitializeComponent();
this.DoubleBuffered = true;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics gObj = e.Graphics;
rect = new Rectangle(x, y, height, width);
rectPen.DashStyle = DashStyle.Dash;
gObj.DrawRectangle(rectPen, rect);
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
m_mouseDown = true;
// Moving rectangle
if (rect.Contains(e.Location))
{
m_movingRect = true;
Console.WriteLine("m_mouseDown");
}
StartXY = e.Location;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (rect.Contains(e.Location))
this.Cursor = Cursors.SizeAll;
else
this.Cursor = Cursors.Default;
if (m_mouseDown && rect.Contains(e.Location))
{
rect.X += e.X - StartXY.X; // <---- it is calculated correctly but doesn't update rectangle position
rect.Y += e.Y - StartXY.Y;
StartXY = e.Location;
Console.WriteLine("pictureBox1_MouseMove StartXY " + StartXY.X);
Console.WriteLine("pictureBox1_MouseMove StartXY " + StartXY.Y);
Console.WriteLine("pictureBox1_MouseMove rect " + rect.X);
Console.WriteLine("pictureBox1_MouseMove rect " + rect.Y);
}
if (m_mouseDown && !rect.Contains(e.Location))
{
EndXY = e.Location;
x = Math.Min(StartXY.X, EndXY.X);
y = Math.Min(StartXY.Y, EndXY.Y);
height = Math.Abs(StartXY.X - EndXY.X);
width = Math.Abs(StartXY.Y - EndXY.Y);
//Console.WriteLine("pictureBox1_MouseMove XXXX: " + " --- " + e.X.ToString());
//Console.WriteLine("pictureBox1_MouseMove YYYY: " + " --- " + e.Y.ToString());
}
Invalidate(true);
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (!m_movingRect)
{
EndXY = e.Location;
}
m_mouseDown = false;
m_movingRect = false;
Invalidate();
}
}