winfrom-拖动鼠标绘制矩形

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    //http://bbs.csdn.net/topics/390567044
    //http://heisetoufa.iteye.com/blog/380977
    //http://blog.csdn.net/xuyongbeijing2008/article/details/17371311

    public partial class Form2 : Form
    {
        bool bDrawStart = false;
        Point pointStart = Point.Empty;
        Point pointContinue = Point.Empty;
        Dictionary dicPoints;

        public Form2()
        {
            InitializeComponent();

            dicPoints = new Dictionary();
            DoubleBuffered = true;
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true);

            this.MouseDown += new MouseEventHandler(frmMain_MouseDown);
            this.MouseMove += new MouseEventHandler(frmMain_MouseMove);
            this.MouseUp += new MouseEventHandler(frmMain_MouseUp);
            this.Paint += new PaintEventHandler(frmMain_Paint);
        }

        private void frmMain_Paint(object sender, PaintEventArgs e)
        {
            Pen pen = new Pen(Color.Black, 1f);
            pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
            
            if (bDrawStart)
            {
                //实时的画矩形
                int w = pointContinue.X - pointStart.X;
                int h = pointContinue.Y - pointStart.Y;
                Rectangle rect = new Rectangle(pointStart, new Size(w, h));
                e.Graphics.DrawRectangle(pen, rect);
            }
            pen.Dispose();
        }

        void frmMain_MouseDown(object sender, MouseEventArgs e)
        {
            if (bDrawStart)
            {
                bDrawStart = false;
            }
            else
            {
                bDrawStart = true;
                pointStart = e.Location;
            }
        }
        void frmMain_MouseMove(object sender, MouseEventArgs e)
        {
            if (bDrawStart)
            {
                pointContinue = e.Location;
                //Refresh();
                Invalidate();
            }
        }
        void frmMain_MouseUp(object sender, MouseEventArgs e)
        {
            if (bDrawStart)
            {
                dicPoints.Add(pointStart, pointContinue);
            }
            bDrawStart = false;
        }

        //...

    }
}

winfrom-拖动鼠标绘制矩形_第1张图片


你可能感兴趣的:(Winfrom)