secondPoint.Y);int maxX = Math.Max(firstPoint.X

时间:2022-06-30 08:21:04

具体的实现要领就不久不多解释了,备注很详细,代码也很简单。

主要成果代码如下:

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; using System.IO; using System.Configuration; namespace WFApp2 { public partial class data : Form { public data() { InitializeComponent(); //窗体 g = this.CreateGraphics(); //chart控件 g2 = this.chart1.CreateGraphics(); } public Point firstPoint = new Point(0, 0); //鼠标第一点 public Point secondPoint = new Point(0, 0); //鼠标第二点 public bool begin = false; //是否开始画矩形 /// <summary> /// 在from上画矩形 /// </summary> Graphics g; /// <summary> /// 在chart1控件上画矩形 /// </summary> Graphics g2; /// <summary> /// 在窗体上按下鼠标事件 /// </summary> /// <param></param> /// <param></param> private void data_MouseDown(object sender, MouseEventArgs e) { begin = true; firstPoint = new Point(e.X, e.Y); } /// <summary> /// 在窗体上鼠标移动开始绘图 /// </summary> /// <param></param> /// <param></param> private void data_MouseMove(object sender, MouseEventArgs e) { if (begin) { //断根窗体绘图面,相当于刷新了一次窗体界面然后从头绘制 g.Clear(this.BackColor); //获取新的右下角坐标 secondPoint = new Point(e.X, e.Y); //获取两个数中的大者或小者 int minX = Math.Min(firstPoint.X, secondPoint.X); int minY = Math.Min(firstPoint.Y, secondPoint.Y); int maxX = Math.Max(firstPoint.X, secondPoint.X); int maxY = Math.Max(firstPoint.Y, secondPoint.Y); //画框 g.DrawRectangle(new Pen(Color.Red), minX, minY, maxX - minX, maxY - minY); //ControlPaint.DrawReversibleFrame(new Rectangle(minX, minY, maxX - minX, maxY - minY),this.BackColor,FrameStyle.Dashed); } } /// <summary> /// 鼠标松开遏制绘图 /// </summary> /// <param></param> /// <param></param> private void data_MouseUp(object sender, MouseEventArgs e) { begin = false; } /// <summary> /// 在chart控件上移动鼠标绘图 /// </summary> /// <param></param> /// <param></param> private void chart1_MouseMove(object sender, MouseEventArgs e) { if (begin) { //从头在chart上面绘图,此处不能用clear要领,clear会断根整个绘图界面chart控件会被断根 this.Refresh(); //获取新的右下角坐标 secondPoint = new Point(e.X, e.Y); int minX = Math.Min(firstPoint.X, secondPoint.X); int minY = Math.Min(firstPoint.Y, secondPoint.Y); int maxX = Math.Max(firstPoint.X, secondPoint.X); int maxY = Math.Max(firstPoint.Y, secondPoint.Y); //画矩形 g2.DrawRectangle(new Pen(Color.Red), minX, minY, maxX - minX, maxY - minY); } } /// <summary> /// 鼠标松开遏制绘图 /// </summary> /// <param></param> /// <param></param> private void chart1_MouseUp(object sender, MouseEventArgs e) { begin = false; } /// <summary> /// 在chart控件上按下鼠标 /// </summary> /// <param></param> /// <param></param> private void chart1_MouseDown(object sender, MouseEventArgs e) { begin = true; firstPoint = new Point(e.X, e.Y); } } }