Title: Copy and paste scribble data in C#
The example Save and restore pictures drawn by the user 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 examples 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<Point> Points = new List<Point>();
// 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<Polyline> Polylines = new List<Polyline>();
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<Polyline>)data_object.GetData(
Polylines.GetType());
if (Polylines == null) Polylines = new List<Polyline>();
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<Polyline> is present, the code uses the data object's GetData method to get it. It converts the returned generic object into a List<Polyline>, saves the result in the program's Polylines variable, and redraws.
You can use the same technique 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.
Download the example to experiment with it and to see additional details.
|