2010-12-20 11:09:35Chris C.S Huang

[C#] 用滑鼠在Form上畫方框


程式碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Rectangle rect;
        public Form1()
        {
            InitializeComponent();
        // 更改滑鼠游標 "+"
        this.Cursor = System.Windows.Forms.Cursors.Cross;   
         // 降低flicker
        this.DoubleBuffered = true; 
        }
       
        public void Form1_MouseDown(object sender, MouseEventArgs e)
        {

            // "e.X" and "e.Y"為滑鼠座標
            rect = new Rectangle(e.X, e.Y, 0, 0);
            this.Invalidate();
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Left)
            {
                //滑鼠邊移動邊畫方框
                rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top);
            }
            this.Invalidate();
        }

        string pt1, pt2;
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            //Green: 綠色, 可更改為其他顏色; 1: 線寬, 可更改.
            using (Pen pen = new Pen(Color. Green, 1))
            {
                e.Graphics.DrawRectangle(pen, rect);
            }
            //pt1: 方框左上方端點座標; pt2: 右下方端點座標
            pt1 = "( Left   , Top     ) = ( " + rect.Left + " , " + rect.Top + " )";
            pt2 = "( Right , Bottom ) = ( " + rect.Right + ", " + rect.Bottom + " )";
            label1.Text = pt1;
            label2.Text = pt2;
        }
    }
}

 記得要在Form1.Designer.cs的 InitializeComponent()中指定 Event Handler

 this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
  this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);
  this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseMove);

參考資料:

Draw a Rectangle in C# using Mouse