c#PictureBox画直线 矩形

转自:http://blog.csdn.net/hejialin666/article/details/3584285

c#PictureBox的基本使用(画直线,矩形)

下面的四个事件一定要绑定,不绑定任何效果都没有的 

private Point m_ptStart = new Point(0, 0);
private Point m_ptEnd = new Point(0, 0);
// true: MouseUp or false: MouseMove 
private bool m_bMouseDown = false;

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
	if (e.Button != MouseButtons.Left)
	{
		return;
	}  

	if (!m_bMouseDown)
	{
		m_ptStart = new Point(e.X, e.Y);
		m_ptEnd = new Point(e.X, e.Y);
	}
	m_bMouseDown = !m_bMouseDown;
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
	if (e.Button != MouseButtons.Left)
	{
		return;
	}

	if (m_ptStart.X >= 0 && m_ptEnd.X >= 0
		 && m_ptStart.Y >= 0 && m_ptEnd.Y >= 0
		 && m_ptStart.X <= 254 && m_ptEnd.X <= 254
		 && m_ptStart.Y <= 163 && m_ptEnd.Y <= 163)
	{
		m_ptEnd = new Point(e.X, e.Y);
		m_bMouseDown = !m_bMouseDown;
		this.pictureBox1.Refresh();
	}
	else
	{
		m_ptEnd = m_ptStart;
		m_bMouseDown = !m_bMouseDown;
		this.pictureBox1.Refresh();
	}
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
	if (m_ptStart.Equals(m_ptEnd)) return;

	e.Graphics.DrawLine(System.Drawing.Pens.Red, m_ptStart, m_ptEnd);
	
   //画矩形加上以下六行
   //if (m_ptEnd.X - m_ptStart.X < 0 || m_ptEnd.Y - m_ptStart.Y < 0)
// {
//     return;
//}

   //e.Graphics.DrawRectangle(System.Drawing.Pens.Blue, m_ptStart.X, m_ptStart.Y, m_ptEnd.X - m_ptStart.X, m_ptEnd.Y - m_ptStart.Y);
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
	if (e.Button != MouseButtons.Left)
	{
		return;
	}
	
	m_ptEnd = new Point(e.X, e.Y);
	this.pictureBox1.Refresh();
}





你可能感兴趣的:(矩形,PictureBox画直线)