Copy and paste complex data in the scribble application in C#

The example Make an enhanced scribble application that lets the user draw in different colors, line thicknesses, and line styles in C# shows how to make a simple drawing program. The example Copy and paste objects to the clipboard in C# shows how to copy objects to the clipboard. This example combines the two to make a scribble program that lets you copy and paste drawings.

The key is to make a single variable hold the entire drawing and mark it as serializable. Then you can copy instances of that class to the clipboard.

This example stores drawing information in the following Polyline class.

[Serializable()]
public class Polyline
{
[XmlIgnore] public Color Color = Color.Black;
public int Thickness = 1;
public DashStyle DashStyle = DashStyle.Solid;
public List Points = new List();

// Get or set the color as an ARGB value.
public int Argb
{
get { return this.Color.ToArgb(); }
set { Color = Color.FromArgb(value); }
}

public void Draw(Graphics gr)
{
using (Pen the_pen = new Pen(Color, Thickness))
{
the_pen.DashStyle = DashStyle;
if (DashStyle == DashStyle.Custom)
{
the_pen.DashPattern = new float[] { 10, 2 };
}
gr.DrawLines(the_pen, Points.ToArray());
}
}
}

The only really important part here is that the class is marked with the Serializable attribute.

The main program stores a series of Polyline objects in the following list.

// The polylines we draw.
private List Polylines = new List();

The following code copies the current drawing to the clipboard.

// Copy the scribble to the clipboard.
private void mnuEditCopy_Click(object sender, EventArgs e)
{
Clipboard.SetDataObject(Polylines);
}

The following code pastes the drawing in the clipboard.

// Paste a scribble from the clipboard.
private void mnuEditPaste_Click(object sender, EventArgs e)
{
IDataObject data_object = Clipboard.GetDataObject();
if (data_object.GetDataPresent(Polylines.GetType()))
{
Polylines = (List)data_object.GetData(Polylines.GetType());
if (Polylines == null) Polylines = new List();
picCanvas.Refresh();
}
}

This code uses the clipboard's GetDataObject method to get the clipboard's data object. If that object's GetDataPresent method indicates that a List is present, the code uses the data object's GetData method to get it. It converts the returned generic object into a List , saves the result in the program's Polylines variable, and redraws.

You can use the same technique more generally to copy and paste complex data structures. Just be sure to save all of the data in a single object (which may be very complex) and that the class is marked serializable.

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.