窗体上鼠标移动画线

来源:互联网 发布:淘宝客营销计划条件 编辑:程序博客网 时间:2024/06/01 08:35

窗体上鼠标移动画线

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 鼠标移动画线

{

   public partial classForm1 : Form

   {

       public Form1()

       {

           InitializeComponent();

       }

 

       private void Form1_Load(object sender, EventArgs e)

       {

 

       }

 

       //MyPoint1,MyPoint2表示鼠标按下和弹起时鼠标的坐标位置 

       public Point MyPoint1, MyPoint2;

       public int MyFlag = 0;

 

       private voidForm1_MouseUp(object sender,MouseEventArgs e)

       {

           //当鼠标弹起时,设置MyFlag = 0,表示不能画线 

           this.MyFlag = 0;

       }

 

       private void Form1_MouseMove(object sender, MouseEventArgs e)

       {

           this.Text = "X=" + e.X.ToString() + ",Y=" + e.Y.ToString();

           Graphics g = this.CreateGraphics();

           Pen MyPen = new Pen(Color.Black);

 

           //MyFlag=0表示鼠标弹起,不能进行画线 

           //当鼠标按下时,设置MyFlag=1表示可以画线 

           if (this.MyFlag == 0)

               return;

 

           //鼠标移动,每次变换时,MyPoint2都记录下鼠标的位置,以便进行鼠标移动画线 

           this.MyPoint2.X = e.X;

           this.MyPoint2.Y = e.Y;

           g.DrawLine(MyPen, MyPoint1.X, MyPoint1.Y, MyPoint2.X,MyPoint2.Y);

 

           //当画完一条线后(很短的,可以当做一个小点看待),将MyPoint1的坐标重置为此时鼠标的位置 

           MyPoint1.X = e.X;

           MyPoint1.Y = e.Y;

       }

 

       private void Form1_MouseDown(object sender, MouseEventArgs e)

       {

           //鼠标第一次按下时,设置鼠标坐标为第一个点的坐标 

           this.MyFlag = 1;

           this.MyPoint1.X = e.X;

           this.MyPoint1.Y = e.Y;

       }

 

       private void button1_Click(object sender, EventArgs e)

       {

           this.MyPoint1.X = 0;

           this.MyPoint1.Y = 0;

 

           this.MyPoint2.X = 90;

           this.MyPoint2.Y = 90;

           Graphics g = this.CreateGraphics();

           float a = 10;

           Pen MyPen = new Pen(Color.Black, a);

           g.DrawLine(MyPen, MyPoint1.X, MyPoint1.Y, MyPoint2.X,MyPoint2.Y);

           g.DrawLine(MyPen, MyPoint2.X, MyPoint1.Y, MyPoint1.X,MyPoint2.Y); 

           g.DrawLine(MyPen, MyPoint2.X, MyPoint2.Y, MyPoint2.X,MyPoint1.Y);

           g.DrawLine(MyPen, MyPoint1.X, MyPoint2.Y, MyPoint1.X,MyPoint1.Y);

        }

    }

}

 

 文章来源:http://blog.csdn.net/hui_shixu/article/details/7738410,这里表示感谢!