日期:2014-05-18 浏览次数:21023 次
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 WindowsFormsApplication2 { public partial class Form1 : Form { private bool ismousedown = false;//开始画图 private PointF startposition; private PointF nowposition; private Image img; private Image image; private Pen pen; private Graphics g; public Form1() { InitializeComponent(); SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true); this.UpdateStyles(); img = new Bitmap(this.Width, this.Height); image = new Bitmap(this.Width,this.Height); pen = new Pen(Color.Red, 2); } private void Form1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ismousedown = true; startposition.X = e.X; startposition.Y = e.Y; } } private void Form1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (ismousedown) { nowposition.X = e.X; nowposition.Y = e.Y; g = Graphics.FromImage(img); g.Clear(Color.WhiteSmoke); g.DrawImage(image, 0, 0); g.DrawRectangle(pen,Math.Min(nowposition.X,startposition.X),Math.Min(nowposition.Y,startposition.Y),Math.Abs(nowposition.X -startposition.X ),Math.Abs(nowposition.Y-startposition.Y)); g.Dispose(); Graphics graphcis = this.CreateGraphics(); graphcis.DrawImage(img, 0, 0); graphcis.Dispose(); } } } private void Form1_MouseUp(object sender, MouseEventArgs e) { ismousedown = false; g = Graphics.FromImage(image); g.DrawImage(img, 0, 0); g.Dispose(); } } }