Click here to Skip to main content
15,175,307 members
Articles / Multimedia / GDI+
Posted 24 Aug 2007


89 bookmarked

Draw with Mouse

Rate me:
Please Sign up or sign in to vote.
4.71/5 (28 votes)
17 Oct 2007CPOL5 min read
An article showing how to draw on screen
Screenshot - Article.jpg



The program presented here allows you to draw different graphics and to embed graphics into an executable. When you run that executable, it will produce exactly the same drawing on the desktop. What's more, you will see the graphics being drawn. So, you can draw or write something using your mouse in different colors and different widths, build an executable file and send it to someone. When they run it, it will reproduce everything you have drawn.

What You Will Learn from This Article

  • How to draw directly on the desktop
  • How to deserialize an object into a different type than the one it was serialized into
  • How to compile C# code during runtime


It would be nice if you were familiar with basic serialization concepts.

How the Program Works

When you run the program, you can start drawing by pressing the mouse button and moving it while holding it down. You can choose different colors and widths to use while drawing. If you click Build, you will be prompted for the destination of the executable and it will be built. Running the newly built executable will draw the same graphic on the screen and you will be able to watch it being drawn.

Code Behind the Application

Classes Used for Drawing

In order to store information about the drawings, I have developed two classes: Curve and Drawing. Here are their class diagrams:

Screenshot - Article1.jpg

The Curve class carries information about all mouse movements that occur while the mouse button is pressed. The coordinates of all points are stored in a variable of List<Point> type. _duration stores the amount of time that the curve was being drawn. _pause indicates the time that elapsed after the previous curve was drawn. Obviously, it will be equal to zero for the first curve. Drawing stores the list of curves, as well as the width and height of the screen.

Managing the Drawing Process

When the user presses the mouse button, a Boolean variable indicating whether the drawing is in progress or not is set to true. After that, this variable is checked in the MouseMove event and a line is drawn accordingly:

private void Form1_MouseMove(object sender, MouseEventArgs e)
    Pen p = new Pen(color, width);
    if (isdrawing)
        using (Graphics gr=this.CreateGraphics())
            gr.DrawLine(p, prev, e.Location);
            prev = e.Location;

cv is a variable of type Curve. When the drawing of the current curve finishes, cv is added to the list of curves in an instance of the Drawing class.

Serializing and Building the Executable

When the user ends drawing and clicks the Build button, an instance of the Drawing class is serialized to file. Before serializing, all coordinates are transformed to screen coordinates using the PointToScreen method. After serialization, an executable file is built using the CSharpCodeProvider and CompilerParameters classes. Here is the code snippet:

private bool Compile(string path)
    bool result;

    using (CSharpCodeProvider prov = new CSharpCodeProvider())
        CompilerParameters param = new CompilerParameters();
        string pathtoicon = "";

        //Set executable icon
        if (File.Exists(Application.StartupPath + "\\icon.ico"))
            pathtoicon = Application.StartupPath + "\\icon.ico";

        param.CompilerOptions =
            "/target:winexe" + " " + "/win32icon:" +
            "\"" + pathtoicon + "\"";
        param.GenerateExecutable = true;
        param.GenerateInMemory = false;
        param.IncludeDebugInformation = false;

        //Add the file to which data was serialized as embedded resource
        param.OutputAssembly = path;

        //Add references
        param.TreatWarningsAsErrors = false;

        //Compile it
        CompilerResults compresults =
        result = compresults.Errors.Count == 0;

        File.Delete(Environment.GetEnvironmentVariable("TEMP") +
    return result;

Recreating the Drawing process

When you launch the generated executable, an object of the Drawing class is deserialized from the embedded stream and then it is drawn on the desktop. The steps are described below.

Advanced Binary Serialization: Deserializing an Object Into a Different Type Than the One It was Serialized Into

If you serialize an object in one assembly and try to deserialize it from another assembly, you will get an error saying that the assembly in which the serialized object was declared cannot be found. You will get the same error even if both assemblies contain the class definition for the specified object. There were two possible ways to solve this problem:

  • Use XML Serialization instead of Binary


  • Move the class definition to a separate DLL and reference the same DLL from both assemblies

Both of them have disadvantages. XML Serialization is slower than Binary and the output file is larger in size. Defining classes in a separate DLL means that you won't be able to create a stand-alone executable. So, I was stuck with this problem.

After Googling for several hours, I found this website that explains Binary Serialization very deeply: Binary Serialization. One of the concepts discussed was how to deserialize an object to a different type. So, I used this to deserialize my object to the same type, but defined in another assembly. To do that, you have to make your own class inherited from System.Runtime.Serialization.SerializationBinder and then override the BindToType method. Here is my implementation:

sealed class typeconvertor : SerializationBinder
    public override Type BindToType(string assemblyName, string typeName)
        Type returntype = null;
        if (assemblyName ==
            "draw on desktop, Version=,
            Culture=neutral, PublicKeyToken=null")
            assemblyName = Assembly.GetExecutingAssembly().FullName;
            returntype =
                Type.GetType(String.Format("{0}, {1}",
                typeName, assemblyName));
            return returntype;

        if (typeName ==
            draw on desktop, Version=, Culture=neutral,
            typeName =
                typeName.Replace("draw on desktop,
                Version=, Culture=neutral, PublicKeyToken=null",
            returntype =
                Type.GetType(String.Format("{0}, {1}",
                typeName, assemblyName));
            return returntype;
      return returntype;

After that, you have to set the formatter's Binder property to this newly created type. The code snippet below will make it clearer:

private Drawing eserialize(Stream input)
    Drawing temp = null;
        BinaryFormatter formatter = new BinaryFormatter();

        //This is the most important part
        formatter.Binder = new typeconvertor();
        temp = formatter.Deserialize(input) as Drawing;
     catch (SerializationException ex)
     return temp;

During deserialization, BindToType is called several times. When it encounters a type defined in the "draw on desktop" assembly, it substitutes it with the corresponding type from the calling assembly. So, the problem of deserialization is solved.

Drawing on the Screen

In order to draw on the screen, we need to retrieve a handle to the device context. To retrieve the handle of the device context, we call the function GetDC and pass an empty handle. GetDC is an unmanaged method, so we need to use P/Invoke to be able to call it from our application.

When we have the handle retrieved, we pass it to a static method of the Graphics class called Graphics.FromHdc. This function creates a new Graphics object that we can use for drawing. Here is a code snippet showing the declaration of the GetDC function and the creation of a graphics object.

static extern IntPtr GetDC(IntPtr hWnd);
Graphics gr = Graphics.FromHdc(GetDC(IntPtr.Zero))

Once we have created the graphics object, we can use it for necessary drawings. So, that's it! I hope you found it interesting and learnt something new.

Points of Interest

Deserializing an object into a different type than the one it was serialized into was the most interesting and tricky part in the whole application.


  • August 24, 2007 - Initial Release


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


About the Author

Giorgi Dalakishvili
Software Developer
Georgia Georgia
No Biography provided

Comments and Discussions

SuggestionI did it much simpler Pin
Shimmy Weitzhandler18-Nov-17 10:47
MemberShimmy Weitzhandler18-Nov-17 10:47 
GeneralMy vote of 5 Pin
Shimmy Weitzhandler18-Nov-17 10:41
MemberShimmy Weitzhandler18-Nov-17 10:41 
GeneralMy vote of 1 Pin
Akshun877-Apr-13 19:52
MemberAkshun877-Apr-13 19:52 
QuestionDraw lines delete(undo) line after line and between points and Pin
MrKyaw13-Feb-12 22:35
MemberMrKyaw13-Feb-12 22:35 
Questiongoog job Pin
tokenian11-Oct-11 22:34
Membertokenian11-Oct-11 22:34 
Generalhi Pin
Member 34572769-May-08 10:42
MemberMember 34572769-May-08 10:42 
GeneralJust what I needed Pin
Mike Hankey7-Jan-08 10:31
professionalMike Hankey7-Jan-08 10:31 
GeneralBuild failed Pin
Todd Smith17-Oct-07 12:26
MemberTodd Smith17-Oct-07 12:26 
GeneralRe: Build failed Pin
Tengiz Tutisani10-Feb-09 1:58
MemberTengiz Tutisani10-Feb-09 1:58 
GeneralError Message and Question Pin
MOISJWang28-Aug-07 6:29
MemberMOISJWang28-Aug-07 6:29 
Hi Giorgi,

It is simple and very useful. Good job! When I clicked Build tool button, I got the following error:

"Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on."

I am using C# Express 2005. Also, how do I save/retrieve the drawing on/from SQL Server? This will be very very useful!

Thanks for your efforts!


Software design/development are state of the arts and fun. Don't lose your dreams and visions.

GeneralRe: Error Message and Question Pin
Tengiz Tutisani10-Feb-09 2:03
MemberTengiz Tutisani10-Feb-09 2:03 
GeneralInteresting combination! Pin
Martin#27-Aug-07 22:00
MemberMartin#27-Aug-07 22:00 
GeneralNice Job Pin
kresso25-Aug-07 3:42
Memberkresso25-Aug-07 3:42 
Generalvery interesting! Pin
MrBabba24-Aug-07 12:15
MemberMrBabba24-Aug-07 12:15 
GeneralRe: very interesting! Pin
Giorgi Dalakishvili24-Aug-07 12:39
mentorGiorgi Dalakishvili24-Aug-07 12:39 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.