1

我有一个关于鼠标事件的简单问题。

我有一个 WinForms 应用程序,我使用 GDI+ 图形对象来绘制简单的形状,一个圆形。

现在我要做的是用鼠标拖动这个形状。

所以当用户移动鼠标时,当仍然按下左键时,我想移动对象。

我的问题是如何检测用户是否仍在按下鼠标左键?我知道winforms中没有onDrag事件。有任何想法吗?

4

1 回答 1

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);
            }
        }


    }
}
于 2013-02-27T12:40:46.557 回答