我是 C# 编程新手,想寻求一点帮助。我目前正在尝试使用鼠标左键移动在 Windows 应用程序表单上绘制的填充颜色的矩形,并且我正在尝试使用鼠标右键将其拖放到另一个位置。目前我已经设法绘制了矩形,但是右键单击正在拖动整个表单。
这是我的代码:
public partial class Form1 : Form
{
private Point MouseDownLocation;
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
Rectangle rec = new Rectangle(0, 0, 0, 0);
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.DeepSkyBlue, rec);
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
rec = new Rectangle(e.X, e.Y, 0, 0);
Invalidate();
}
if (e.Button == MouseButtons.Right)
{
MouseDownLocation = e.Location;
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
rec.Width = e.X - rec.X;
rec.Height = e.Y - rec.Y;
Invalidate();
}
if (e.Button == MouseButtons.Right)
{
this.Left = e.X + this.Left - MouseDownLocation.X;
this.Top = e.Y + this.Top - MouseDownLocation.Y;
}
}
}
我只需要用鼠标右键拖放矩形。
编辑:谢谢大家,我很快就得到了答案,这是有效的代码:
public partial class Form1 : Form
{
private Point MouseDownLocation;
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
Rectangle rec = new Rectangle(0, 0, 0, 0);
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.DeepSkyBlue, rec);
//Generates the shape
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
//can also use this one:
//if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
rec = new Rectangle(e.X, e.Y, 0, 0);
Invalidate();
}
if (e.Button == MouseButtons.Right)
{
MouseDownLocation = e.Location;
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
rec.Width = e.X - rec.X;
rec.Height = e.Y - rec.Y;
this.Invalidate();
}
if (e.Button == MouseButtons.Right)
{
rec.Location = new Point((e.X - MouseDownLocation.X) + rec.Left, (e.Y - MouseDownLocation.Y) + rec.Top);
MouseDownLocation = e.Location;
this.Invalidate();
}
}
}