[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.
Comments