using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace WindowsApplication1
{
//手工编写winform
class test:Form
{
//手工编写一个自拖动鼠标绘矩形
//分析:要存储当前鼠标的位置,此可由如下事件mouseeventargs获知
// 要用到drawrectangle方法,此方法会用到参数当前鼠标的位置
// 还要填充此矩形,故要存储上述矩形的信息到一个字段
// 基于面向对象原则,绘制与填充放在两个东东,这个东东叫什么,叫方法吧,这两个方法之间要传递信息,要一个字段,表明是否已绘制矩形,已绘制矩形,方可填充矩形
//还要把如下几个事件与上述的字段结合起来,
private Rectangle currect;//绘制矩形 矩形的构造函数要多理解,比如在此用到矩形的左上角坐标point(x,y)及矩形长度及矩形宽度,共计4个元素,矩形起点坐标与终止坐标,所以要存储这2个字段
private Point beginpoint, endpoint;
private bool isdraw=false;//是否绘制
private bool ishasrectangle = false;//是否已有矩形
private Point curpoint;//鼠标当前坐标
public test()
{
Text = "手工绘制及填充矩形";
BackColor = SystemColors.Window;
ForeColor = SystemColors.WindowText;
ResizeRedraw = true;
}
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new test());
}
//鼠标移动事件,以此事件 绘制 以鼠标当前位置坐标的相关图形
//判断是否绘制,如已绘制,调用drawrectangle方法,绘矩形
protected override void OnMouseMove(MouseEventArgs e)
{
if (isdraw)
{
endpoint=new Point(e.X,e.Y);
Graphics gp = CreateGraphics();
gp.DrawRectangle(new Pen(ForeColor), rect(beginpoint,endpoint));//故形成矩形对象也要单独成一个方法
gp.Dispose();
ishasrectangle = true;//在鼠标移动设置ishasrectangle为真,用于鼠标释放操作
}
}
protected override void OnMouseWheel(MouseEventArgs e)
{
}
//释放鼠标,调用invalidate方法,进而调用onpaint事件
protected override void OnMouseUp(MouseEventArgs e)
{
if (ishasrectangle) //已有矩形了,开始填充矩形
{
currect = rect(beginpoint, endpoint);
Graphics gp = CreateGraphics();
gp.FillRectangle(new SolidBrush(Color.Brown), currect);
}
}
//鼠标按下,设置isdraw为true,表示可以绘制矩形了,
protected override void OnMouseDown(MouseEventArgs e)
{
//鼠标按下,是鼠标起始即第1次按下的坐标,也即本例中矩形的起始坐标,刚开始起始与结束坐标一样;那么结束坐标会随着移动鼠标事件发生动态变化
beginpoint = endpoint = new Point(e.X, e.Y);//鼠标当前位置坐标
isdraw = true;
}
protected override void OnPaint(PaintEventArgs e)
{
}
//绘制矩形的方法
Rectangle rect(Point bpoint,Point epoint)
{
return new Rectangle(bpoint.X,bpoint.Y,Math.Abs(epoint.X-bpoint.X),Math.Abs(epoint.Y-bpoint.Y));
}
}
}