在《C#高级编程》一书里有关于画图的讲解,在Mouse事件中实现

解决方案 »

  1.   

    using System;
    using System.IO ;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    private void MouseDownHandler(Object sender,MouseEventArgs e)
    {
    if(!this.Capture)
    return; try{
    Point p = new Point(e.X,e.Y);
    currentStroke = myDoc.NewStroke();
    currentStroke.pointArray.Add(p);// 向新的笔画添加第一个点
    previousPoint = p;

    this.Capture = true; // 捕获鼠标直到按钮弹起
    }
    catch(Exception ex) {
    MessageBox.Show(ex.ToString());
    } }
    private void MouseMoveHandler(Object sender,MouseEventArgs e)
    {
    if(!this.Capture)
    return; try{
    Point p = new Point(e.X , e.Y);
    currentStroke.pointArray.Add(p);
    Graphics g = this.CreateGraphics();
    g.DrawLine(myDoc.GetCurrentPen(),previousPoint,p); previousPoint = p;
    }
    catch (Exception ex) { 
    MessageBox.Show(ex.ToString());
            } }private void MouseUpHandler(Object sender,MouseEventArgs e)
    {
    //如果当前笔画为空,则忽略此事件
    if(currentStroke==null)
    return; try{
    Point p= new Point(e.X,e.Y);
    currentStroke.pointArray.Add(p);
    Graphics g = this.CreateGraphics();
    g.DrawLine(myDoc.GetCurrentPen(),previousPoint,p);

    previousPoint=p;
    // 通知笔画项已完成向其添加点的操作。
    // 这样,它才能完成对其边框的计算。
    currentStroke.FinishStroke();

    // 由于添加了笔画,因此将此事通知文档的所有视图
    myDoc.UpdateAllViews(this,currentStroke);       

    this.Capture = false;

    }
    catch (Exception ex) { 
    MessageBox.Show(ex.ToString());
            } }