Tôi mới lập trình trong C# và muốn yêu cầu trợ giúp một chút. Tôi hiện đang cố gắng di chuyển một hình chữ nhật đầy màu sắc mà tôi vẽ trên biểu mẫu Ứng dụng Windows bằng nút chuột trái của tôi và tôi đang cố gắng kéo và thả nó đến một vị trí khác bằng nút chuột phải của tôi. Hiện tại tôi đã quản lý để vẽ hình chữ nhật, nhưng nhấp chuột phải là kéo toàn bộ biểu mẫu dọc theo.Cách vẽ và di chuyển hình dạng bằng chuột trong C#
Dưới đây là mã của tôi:
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;
}
}
}
Tôi chỉ cần kéo và thả các hình chữ nhật với nút chuột phải.
EDIT: Nhờ tất cả tôi đã nhận câu trả lời của tôi rất nhanh và ở đây bạn là đoạn code mà hoạt động:
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();
}
}
}
Nó hoạt động! Cảm ơn nhiều. –