我有一个关于鼠标事件的简单问题。
我有一个WinForms应用程序,我使用了GDI +图形对象 画一个简单的形状,一个圆圈。
现在我想做的是用鼠标拖动这个形状。
因此,当用户移动鼠标时,仍然按下左按钮 我想移动对象。
我的问题是如何检测用户是否仍按下鼠标的左键? 我知道winforms中没有onDrag事件。 任何想法?
答案 0 :(得分:1)
检查这个非常简化的例子。它并没有涵盖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);
}
}
}
}