Click here to Skip to main content
Click here to Skip to main content

DrawTools

By , 24 Jan 2007
 

DrawTools

Introduction

DrawTools sample shows how to create a Windows Forms application for drawing graphic objects in a Windows client area using mouse and drawing tools. Drawing tools implemented in this sample are: Rectangle, Ellipse, Line, and Pencil. There are well-known techniques for creating such type of applications, like: interaction with mouse, flicker-free drawing, implementing of drawing and selection tools, objects selection, managing of objects Z-order etc. MFC developers may learn all this stuff from MFC sample DRAWCLI. DrawTools C# program reproduces some of DRAWCLI functionality and uses some design decisions from this sample.

DrawTools solution contains two projects: DrawTools Windows Forms application and DocToolkit Class Library. DrawTools implements specific application stuff, and DocToolkit contains some standard classes for file managing.

Main features of the DrawTools solution are described below.

DrawTools classes

Classes

  • DrawArea - user control which fills main application window client area. Contains instance of the GraphicsList class. Draws graphic objects, handles mouse input passing commands to GraphicsList.
  • GraphicsList - list of graphic objects. Contains ArrayList of graphic objects. Talks with each graphic object by generic way using DrawObject methods.
  • DrawObject - abstract base class for all graphic objects.
  • DrawRectangle - rectangle graphic object.
  • DrawEllipise - ellipse graphic object.
  • DrawLine - line graphic object.
  • DrawPolygon - polygon graphic object.
  • Tool - abstract base class for all drawing tools.
  • ToolPointer - pointer tool (neutral tool). Contains implementation for selection, moving, resizing of graphic objects.
  • ToolObject - abstract base class for all tools which create new graphic object.
  • ToolRectangle - rectangle tool.
  • ToolEllipse - ellipse tool.
  • ToolLine - line tool.
  • ToolPolygon - polygon tool.

DocToolkit Library

DocToolkit Library contains a set of classes which may be used for creation of document-centric Windows Forms applications. Instances of classes exported from the DocToolkit Library are kept in the main form of the DrawTools project and is used for general file-related operations.

Handling of Windows controls state at application idle time

Every Windows Forms application has a number of controls like menu items, buttons, toolbar buttons etc. Depending on current situation and user commands, these controls may have different states: enabled/disabled, checked/unchecked, visible/invisible etc. Every user action may change this state. Setting of controls' state in every message handler may be error-prone. Instead of this, it is better to manage controls' state in some function which is called after every user action. MFC has the great ON_UPDATE_COMMAND_UI feature which allows to update toolbar buttons' state at application idle time. Such a feature may be implemented also in .NET programs.

Consider the situation when user clicks the Rectangle toolbar button. This button should be checked, and previously active tool should be unchecked. Rectangle button message handler doesn't change form controls' state, it just keeps current selection in some variable. Idle message handler selects active tool and unselects inactive tool.

private void Form1_Load(object sender, System.EventArgs e)
{
    // Submit to Idle event to set controls state at idle time
    Application.Idle += delegate(object o, EventArgs a)
    {
        SetStateOfControls();
    };
}

public void SetStateOfControls()
{
    // Select active tool
    tbPointer.Pushed = (drawArea.ActiveTool == DrawArea.DrawToolType.Pointer);
    tbRectangle.Pushed = (drawArea.ActiveTool==DrawArea.DrawToolType.Rectangle);
    tbEllipse.Pushed  = (drawArea.ActiveTool == DrawArea.DrawToolType.Ellipse);
    tbLine.Pushed = (drawArea.ActiveTool == DrawArea.DrawToolType.Line);
    tbPolygon.Pushed = (drawArea.ActiveTool == DrawArea.DrawToolType.Polygon);

    menuDrawPointer.Checked = 
                      (drawArea.ActiveTool == DrawArea.DrawToolType.Pointer);
    menuDrawRectangle.Checked = 
                      (drawArea.ActiveTool == DrawArea.DrawToolType.Rectangle);
    menuDrawEllipse.Checked = 
                      (drawArea.ActiveTool == DrawArea.DrawToolType.Ellipse);
    menuDrawLine.Checked = (drawArea.ActiveTool == DrawArea.DrawToolType.Line);
    menuDrawPolygon.Checked = 
                      (drawArea.ActiveTool == DrawArea.DrawToolType.Polygon);

    // ...
}

// Rectangle tool is selected
private void CommandRectangle()
{
     drawArea.ActiveTool = DrawArea.DrawToolType.Rectangle;
}

Hit Test

DrawObject class has virtual HitTest function which detects whether a point belongs to graphic object:

public virtual int HitTest(Point point)
{
    return -1;
}

Derived classes use virtual PointInObject to make hit test. This function is called from HitTest. DrawRectangle class implements this function by a simple way:

protected override bool PointInObject(Point point)
{
    return rectangle.Contains(point);
    // rectangle is class member of type Rectangle
}

DrawLine implementation of this function is more complicated:

protected override bool PointInObject(Point point)
{
    GraphicsPath areaPath;
    Pen areaPen;
    Region areaRegion;

    // Create path which contains wide line
    // for easy mouse selection
    AreaPath = new GraphicsPath();
    AreaPen = new Pen(Color.Black, 7);
    AreaPath.AddLine(startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
        // startPoint and EndPoint are class members of type Point
    AreaPath.Widen(AreaPen);

    // Create region from the path
    AreaRegion = new Region(AreaPath);

    return AreaRegion.IsVisible(point);
}

DrawPolygon function works by the same way, but AreaPath contains all lines in the polygon.

Serialization

GraphicList class implements ISerializable interface which allows to make binary serialization of the class object. DrawObject class has two virtual functions which are used for serialization:

public virtual void SaveToStream(SerializationInfo info, int orderNumber)
{
    // ...
}

public virtual void LoadFromStream(SerializationInfo info, int orderNumber)
{
  // ...
}

These functions are implemented in every derived class. Binary file has the following format:

Number of objects
Type name
Object
Type name
Object
...
Type name
Object

This allows to write generic serialization code in the GraphicList class without knowing any details about serialized objects:

private const string entryCount = "Count";
private const string entryType = "Type";


// Save list to stream
[SecurityPermissionAttribute(SecurityAction.Demand, 
                         SerializationFormatter=true)]
public virtual void GetObjectData(SerializationInfo info, 
                                     StreamingContext context)
{
    // number of objects
    info.AddValue(entryCount, graphicsList.Count);

    int i = 0;

    foreach ( DrawObject o in graphicsList )
    {
        // object type
        info.AddValue(
            String.Format(CultureInfo.InvariantCulture,
                "{0}{1}",
                entryType, i),
            o.GetType().FullName);

        // object itself
        o.SaveToStream(info, i);

        i++;
    }
}

// Load from stream
protected GraphicsList(SerializationInfo info, StreamingContext context)
{
    graphicsList = new ArrayList();

    // number of objects
    int n = info.GetInt32(entryCount);
    string typeName;
    object drawObject;

    for ( int i = 0; i < n; i++ )
    {
        // object type
        typeName = info.GetString(
            String.Format(CultureInfo.InvariantCulture,
                "{0}{1}",
            entryType, i));

        // create object by type name using Reflection
        drawObject = Assembly.GetExecutingAssembly().CreateInstance(
            typeName);

        // fill object from stream
        ((DrawObject)drawObject).LoadFromStream(info, i);

        graphicsList.Add(drawObject);
    }

}

Undo - Redo

Undo-Redo functionality is added to the program using the article The Command Pattern and MVC Architectures by David Veeneman. Class Command is abstract base class for all commands representing user activity: CommandAdd, CommandChangeState, CommandDelete, CommandDeleteAll. Every Command-derived class can make two basic operations: Undo which returns draw area to the state before executing this command, and Redo which executes this command again. CommandChangeState is used for resizing, moving of objects and changing objects properties. Class UndoManager keeps list of executed commands (history) and makes operations Undo, Redo and Add command to History. Undo-Redo functionality is implemented only in 2005 version of DrawTools project.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Alex Fr
Software Developer
Israel Israel
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membernewlifechou8 May '13 - 19:39 
QuestionIn DrawTools c# code can we draw the shapes on a Image file which is opened in the Picture box? See more: C#memberRav11113 Jan '13 - 21:27 
I want to open a image file(.JPG,.BMP etc) in a Picture box and than i want to create shapes on that images so is it possible with DrawTools project?

QuestionPaint C#membermibetty17 Dec '12 - 12:04 
GeneralThanks, very helpfulmembermiro124 Dec '12 - 10:43 
Generalvery very usefulmemberMember 822540724 Nov '12 - 5:32 
QuestionPermissionmemberSakti Sarjono7 Oct '12 - 1:42 
AnswerRe: PermissionmemberAlex Fr11 Oct '12 - 9:02 
GeneralAdding undo/redo supportmemberY Sujan16 Sep '12 - 13:23 
GeneralMy vote of 5memberDaoj14 Aug '12 - 9:21 
GeneralMy vote of 4memberSami Ciit4 Aug '12 - 7:49 
QuestionModifying the project gives error for Null ExceptionmemberPritesh Jagani13 Jul '12 - 1:51 
Questionget pointsmemberesaaco1 Apr '12 - 3:58 
AnswerRe: get pointsmemberMember 79030253 May '12 - 9:08 
Questionabout "?"membersbphsho2 Mar '12 - 15:36 
AnswerRe: about "?"memberZac Greve20 Jun '12 - 10:12 
GeneralRe: about "?"membersbphsho20 Jun '12 - 19:26 
QuestionWPF versionmemberMajid Shahabfar28 Feb '12 - 21:19 
AnswerRe: WPF versionmemberAlex Fr28 Feb '12 - 21:34 
GeneralMy vote of 5membermanoj kumar choubey20 Feb '12 - 19:28 
QuestionDrawingcanvas.Children.Add doesn't workmemberSipder13 Jan '12 - 1:50 
QuestionHow to implement the Rubber function ?memberjerryclick19 Nov '11 - 4:21 
GeneralMy vote of 1memberajeet.sri200628 Sep '11 - 19:28 
QuestionSave to/load from dbmembergalbas29 Jul '11 - 22:56 
QuestionI can I modify the code and upload to my personal github repositorymembertolbKni12 Jul '11 - 0:39 
GeneralAn annoying bugmemberpub2375 May '11 - 0:25 
GeneralNeed similar functionality in .Net Compact framworkmemberKiranpudis17 Mar '11 - 14:06 
GeneralDocument Iconmemberyehongyehong17 Feb '11 - 15:11 
Questionis it possable to save the image in jpg or any other image format?memberheinrich4J17 Nov '10 - 4:05 
Generalfanmemberto van vu16 Aug '10 - 23:27 
GeneralUndo/Redo not Workingmembereg_Anubhava27 Jul '10 - 22:13 
GeneralRe: Undo/Redo not WorkingmemberDemaker28 Jul '10 - 0:08 
GeneralRe: Undo/Redo not Workingmembereg_Anubhava28 Jul '10 - 0:38 
QuestionHow to make line shape user control from the DrawLine class of yoursmemberjcarter12121225 Jul '10 - 9:35 
Generalvery nice but complicatedmembermragers4 Jul '10 - 18:46 
GeneralRe: very nice but complicatedmemberAlex Fr5 Jul '10 - 7:06 
Questionopen all picture file typesmemberxddiana8 Jun '10 - 10:50 
AnswerRe: open all picture file typesmemberAlex Fr12 Jun '10 - 6:51 
QuestionZoom problem using Mouse Wheel and Zoom To Selected AreamemberManuel Salvatori5 May '10 - 23:40 
Generalthanks a lotmemberhotthoughtguy4 Apr '10 - 5:38 
GeneralUndo/Redo Work incorrect!!!memberDemaker2 Feb '10 - 20:05 
GeneralUndo/Redo not working when open *.dtl filememberDemaker1 Dec '09 - 4:47 
GeneralRe: Undo/Redo not working when open *.dtl filememberAlex Fr1 Dec '09 - 7:51 
GeneralRe: Undo/Redo not working when open *.dtl filememberDemaker1 Dec '09 - 20:40 
Generalrotationmemberdoktorekx19 Sep '09 - 10:34 
GeneralRe: rotationmemberAlex Fr19 Sep '09 - 19:29 
GeneralRe: rotationmemberdoktorekx5 Nov '09 - 11:33 
GeneralRe: rotationmemberMember 28478462 Oct '11 - 22:45 
GeneralTop Left ruler around the canvasmemberNatrajan Pillai19 Aug '09 - 21:31 
GeneralAnnotationmemberoldginger5 Aug '09 - 3:25 
QuestionHow do you make the drawing canvas transparent?membernb1forxp218 Jul '09 - 6:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 25 Jan 2007
Article Copyright 2004 by Alex Fr
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid