GDI图形对象上的鼠标拖动事件
本文关键字:鼠标 拖动 事件 图形 对象 GDI | 更新日期: 2023-09-27 18:01:34
我有一个关于鼠标事件的简单问题。
我有一个WinForms应用程序,我使用GDI+图形对象画一个简单的形状,一个圆。
现在我要做的是用鼠标拖动这个形状。
所以当用户移动鼠标时,当左键仍按下时我想移动这个物体。
我的问题是如何检测用户是否还在按鼠标的左键?我知道在winforms中没有onDrag事件。什么好主意吗?
查看这个非常简化的示例。它没有涵盖GDI+绘图的很多方面,但是给你一个如何在winforms中处理鼠标事件的想法。
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsExamples
{
public partial class DragCircle : Form
{
private bool bDrawCircle;
private int circleX;
private int circleY;
private int circleR = 50;
public DragCircle()
{
InitializeComponent();
}
private void InvalidateCircleRect()
{
this.Invalidate(new Rectangle(circleX, circleY, circleR + 1, circleR + 1));
}
private void DragCircle_MouseDown(object sender, MouseEventArgs e)
{
circleX = e.X;
circleY = e.Y;
bDrawCircle = true;
this.Capture = true;
this.InvalidateCircleRect();
}
private void DragCircle_MouseUp(object sender, MouseEventArgs e)
{
bDrawCircle = false;
this.Capture = false;
this.InvalidateCircleRect();
}
private void DragCircle_MouseMove(object sender, MouseEventArgs e)
{
if (bDrawCircle)
{
this.InvalidateCircleRect(); //Invalidate region that was occupied by circle before move
circleX = e.X;
circleY = e.Y;
this.InvalidateCircleRect(); //Add to invalidate region the rectangle that circle will occupy after move.
}
}
private void DragCircle_Paint(object sender, PaintEventArgs e)
{
if (bDrawCircle)
{
e.Graphics.DrawEllipse(new Pen(Color.Red), circleX, circleY, circleR, circleR);
}
}
}
}