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 class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//MyPoint1, MyPoint2表示鼠標按下和彈起時鼠標的座標位置
public Point MyPoint1, MyPoint2;
public int MyFlag = 0;
private void Form1_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,這裏表示感謝!