Inheritance: IDataObject
        private void CopyButtonClick(object sender, EventArgs e)
        {
            var dateTime = DateTime.Parse(DateTextBox.Text, DateTextBox.Culture, DateTimeStyles.AssumeLocal);

            var timeSpan = dateTime.ToUniversalTime() - Epoch;

            var dataObject = new DataObject();

            var messagePlain = string.Format(
                "[{0:hh:mm:ss}] {1}: {2}",
                dateTime,
                AuthorFullNameTextBox.Text,
                MessageTextBox.Text);
            var messageXml = string.Format(
                "<quote author=\"{0}\" timestamp=\"{1}\">{2}</quote>",
                AuthorTextBox.Text,
                timeSpan.TotalSeconds,
                MessageTextBox.Text);

            dataObject.SetData("System.String", messagePlain);
            dataObject.SetData("UnicodeText", messagePlain);
            dataObject.SetData("Text", messagePlain);
            dataObject.SetData("SkypeMessageFragment", new MemoryStream(Encoding.UTF8.GetBytes(messageXml)));
            dataObject.SetData("Locale", new MemoryStream(BitConverter.GetBytes(CultureInfo.CurrentCulture.LCID)));
            dataObject.SetData("OEMText", messagePlain);

            Clipboard.SetDataObject(dataObject, true);
        }
Example #2
1
        private IDataObject CloneClipboard(IDataObject obj)
        {
            if (obj == null)
                return null;

            string[] formats = obj.GetFormats();
            if (formats.Length == 0)
                return null;

            IDataObject newObj = new DataObject();
            
            foreach (string format in formats)
            {
				if (format.Contains("EnhancedMetafile")) //Ignore this. Cannot be processed in .NET
					continue;

				object o = obj.GetData(format);

                if (o != null)
                {
                    newObj.SetData(o);
                }
            }

            return newObj;
        }
		bool CopyTextToClipboard()
		{
			string str = textArea.SelectionManager.SelectedText;
			
			if (str.Length > 0) {
				// paste to clipboard
				// BIG HACK: STRANGE EXTERNAL EXCEPTION BUG WORKAROUND
				for (int i = 0; i < 5; ++i) {
					try {
						DataObject dataObject = new DataObject();
						dataObject.SetData(DataFormats.UnicodeText, true, str);
						// Default has no highlighting, therefore we don't need RTF output
						if (textArea.Document.HighlightingStrategy.Name != "Default") {
							dataObject.SetData(DataFormats.Rtf, RtfWriter.GenerateRtf(textArea));
						}
						OnCopyText(new CopyTextEventArgs(str));
						Clipboard.SetDataObject(dataObject, true);
						return true;
					} catch (Exception e) {
						Console.WriteLine("Got exception while Copy text to clipboard : " + e);
					}
					Thread.Sleep(100);
				}
			}
			return false;
		}
        private void btnCopyToClipboard_Click(System.Object sender, System.EventArgs e)
        {
            System.Windows.Forms.DataObject datobj = new System.Windows.Forms.DataObject();

            datobj.SetData(System.Windows.Forms.DataFormats.Text, rtfMessage.Text);
            System.Windows.Forms.Clipboard.SetDataObject(datobj);
        }
Example #5
0
		public void RtfTextTest ()
		{
			string rtf_text = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Arial;}}{\*\generator Mono RichTextBox;}\pard\f0\fs16 hola\par}";
			string plain_text = "hola";

			Clipboard.SetText (rtf_text, TextDataFormat.Rtf);

			Assert.AreEqual (false, Clipboard.ContainsText (TextDataFormat.Text), "#A1");
			Assert.AreEqual (false, Clipboard.ContainsText (TextDataFormat.UnicodeText), "#A2");
			Assert.AreEqual (true, Clipboard.ContainsText (TextDataFormat.Rtf), "#A3");
			Assert.AreEqual (rtf_text, Clipboard.GetText (TextDataFormat.Rtf), "#A4");

			// Now use a IDataObject, so we can have more than one format at the time
			DataObject data = new DataObject ();
			data.SetData (DataFormats.Rtf, rtf_text);
			data.SetData (DataFormats.UnicodeText, plain_text);

			Clipboard.SetDataObject (data);

			Assert.AreEqual (true, Clipboard.ContainsText (TextDataFormat.Text), "#B1");
			Assert.AreEqual (true, Clipboard.ContainsText (TextDataFormat.UnicodeText), "#B2");
			Assert.AreEqual (true, Clipboard.ContainsText (TextDataFormat.Rtf), "#B3");
			Assert.AreEqual (rtf_text, Clipboard.GetText (TextDataFormat.Rtf), "#B4");
			Assert.AreEqual (plain_text, Clipboard.GetText (), "#B5");

			Clipboard.Clear ();
		}
        private void label2_MouseDown(object sender, MouseEventArgs e)
        {
            // Start drag-and-drop if left mouse goes down over this label
              if (e.Button == MouseButtons.Left)
              {
            // Crete a new data object
            DataObject data = new DataObject();

            // Get the TextBox text
            string dragString = this.textBox1.Text;

            // If the TextBox text was empty then use a default string
            if (string.IsNullOrEmpty(dragString))
              dragString = "Empty string";

            // Set the DataOject's data to a new SampleCsDragData object which
            // can be serialized. If you use an object that does not support the
            // serialize interface then you will NOT be able to drag and drop the
            // item onto a different session of Rhino.
            data.SetData(new SampleCsDragData(dragString));

            // Start drag-and-drop
            this.DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Move);
              }
        }
Example #7
0
        protected void DisplayClipboardData()
        {
            if (!skipFirst)
            {
                skipFirst = true;
                return;
            }
            try
            {
                IDataObject iData = new DataObject();
                iData = Clipboard.GetDataObject();

                if (iData.GetDataPresent(DataFormats.Text))
                {
                    string text = (string)iData.GetData(DataFormats.Text);
                    txtClipBoard.Text = text;
                    int next = clipBoardTextService.process(text);
                    txtStartNumber.Text = next.ToString();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Example #8
0
        public void CutSelectedObjectsToClipboard()
        {
            System.Windows.Forms.DataObject dao = new System.Windows.Forms.DataObject();

            ArrayList objectList = new ArrayList();

            System.Collections.Generic.List <IHitTestObject> notSerialized = new System.Collections.Generic.List <IHitTestObject>();

            foreach (IHitTestObject o in this.m_SelectedObjects)
            {
                if (o.HittedObject is System.Runtime.Serialization.ISerializable)
                {
                    objectList.Add(o.HittedObject);
                }
                else
                {
                    notSerialized.Add(o);
                }
            }

            dao.SetData("Altaxo.Graph.GraphObjectList", objectList);

            // now copy the data object to the clipboard
            System.Windows.Forms.Clipboard.SetDataObject(dao, true);

            // Remove the not serialized objects from the selection, so they are not removed from the graph..
            foreach (IHitTestObject o in notSerialized)
            {
                m_SelectedObjects.Remove(o);
            }

            this.RemoveSelectedObjects();
        }
Example #9
0
        public void CopySelectedObjectsToClipboard()
        {
            System.Windows.Forms.DataObject dao = new System.Windows.Forms.DataObject();

            ArrayList objectList = new ArrayList();

            foreach (IHitTestObject o in this.m_SelectedObjects)
            {
                if (o.HittedObject is System.Runtime.Serialization.ISerializable)
                {
                    objectList.Add(o.HittedObject);
                }
            }

            dao.SetData("Altaxo.Graph.GraphObjectList", objectList);

            // Test code to test if the object list can be serialized
#if false
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binform = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                binform.Serialize(stream, objectList);

                stream.Flush();
                stream.Seek(0, System.IO.SeekOrigin.Begin);
                object obj = binform.Deserialize(stream);
                stream.Close();
                stream.Dispose();
            }
#endif

            // now copy the data object to the clipboard
            System.Windows.Forms.Clipboard.SetDataObject(dao, true);
        }
Example #10
0
 protected override IDataObject GetDataObjectFromText(string text)
 {
     DataObject obj2 = new DataObject();
     obj2.SetData(DataFormats.Text, text);
     obj2.SetData(DataFormats.Html, text);
     return obj2;
 }
Example #11
0
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var dataObject = new System.Windows.Forms.DataObject();

            dataObject.SetData(DataFormats.Text, ToText(m_dtCardProperties, "\t"));
            Clipboard.SetDataObject(dataObject, true);
        }
Example #12
0
 public DataObject ToDataObject()
 {
     DataObject obj = new DataObject();
     obj.SetData(DataFormats.Serializable, this);
     obj.SetData(DataFormats.Text, Texte);
     return obj;
 }
Example #13
0
        public void Send(string archiveFilename, CancellationToken cancellationToken, SimpleProgressCallback progressCallback = null)
        {
            // create drop effect memory stream
            byte[] moveEffect = new byte[] { (byte) (performCut ? 2 : 5), 0, 0, 0 };
            MemoryStream dropEffect = new MemoryStream();
            dropEffect.Write(moveEffect, 0, moveEffect.Length);

            // create file data object
            DataObject data = new DataObject();
            data.SetFileDropList(new StringCollection { archiveFilename });
            data.SetData("Preferred DropEffect", dropEffect);

            // create STA thread that'll work with Clipboard object
            Thread copyStaThread = new Thread(() =>
                {
                    Clipboard.Clear();
                    Clipboard.SetDataObject(data, true);
                })
                {
                    Name = "Clipboard copy thread"
                };

            copyStaThread.SetApartmentState(ApartmentState.STA);

            // start the thread and wait for it to finish
            copyStaThread.Start();
            copyStaThread.Join();
        }
 protected override void DeserializeFromData(DataObject data)
 {
     ConvertOperation convert = new ConvertOperation(data, ConvertOperation.Operation.Convert);
     if (convert.CanPerform(this.editedCmpType))
     {
         var refQuery = convert.Perform(this.editedCmpType);
         if (refQuery != null)
         {
             Component[] refArray = refQuery.Cast<Component>().ToArray();
             this.component = (refArray != null && refArray.Length > 0) ? refArray[0] : null;
             this.PerformSetValue();
             this.PerformGetValue();
             this.OnEditingFinished(FinishReason.LeapValue);
         }
     }
     else if (convert.CanPerform(typeof(GameObject)))
     {
         GameObject obj = convert.Perform<GameObject>().FirstOrDefault();
         Component cmp = obj != null ? obj.GetComponent(this.editedCmpType) : null;
         if (cmp != null)
         {
             this.component = cmp;
             this.PerformSetValue();
             this.PerformGetValue();
             this.OnEditingFinished(FinishReason.LeapValue);
         }
     }
 }
Example #15
0
        /// <summary>
        /// Called when the tool is activated.
        /// </summary>
        protected override void OnActivateTool()
        {
            if(Selection.SelectedItems.Count == 0)
                return;

            try
            {
                //Clear the Anchors otherwise subsequent Copy operations will raise an exception due to the fact that the Anchors class is a static helper class
                Anchors.Clear();
                //this will create a volatile collection of entities, they need to be unwrapped!
                //I never managed to get things working by putting the serialized collection directly onto the Clipboad. Thanks to Leppie's suggestion it works by
                //putting the Stream onto the Clipboard, which is weird but it works.
                MemoryStream copy = Selection.SelectedItems.ToStream();
                DataFormats.Format format = DataFormats.GetFormat(typeof(CopyTool).FullName);
                IDataObject dataObject = new DataObject();
                dataObject.SetData(format.Name, false, copy);
                Clipboard.SetDataObject(dataObject, false);
            }
            catch (Exception exc)
            {
                throw new InconsistencyException("The Copy operation failed.", exc);
            }
            finally
            {
                DeactivateTool();
            }
        }
Example #16
0
        public static SWF.IDataObject ToSwf(this TransferDataSource data)
        {
            var result = new SWF.DataObject();

            foreach (var type in data.DataTypes)
            {
                var value = data.GetValue(type);

                if (type == TransferDataType.Text)
                {
                    result.SetText((string)value);
                }
                else if (type == TransferDataType.Uri)
                {
                    var uris = new StringCollection();
                    uris.Add(((Uri)value).LocalPath);
                    result.SetFileDropList(uris);
                }
                else
                {
                    result.SetData(type.Id, value);
                }
            }

            return(result);
        }
        /// <summary>
        /// This method is called when the drag and drop operation is completed and
        /// the item being dragged was dropped on the Rhino layer list control.
        /// </summary>
        public override bool OnDropOnLayerListCtrl(IWin32Window layerListCtrl, int layerIndex, DataObject data, DragDropEffects dropEffect, Point point)
        {
            SampleCsDragData dragData = GetSampleCsDragData(data);
              if (null == dragData)
            return false;

              if (layerIndex < 0)
              {
            MessageBox.Show(
              RhUtil.RhinoApp().MainWnd(),
              "String \"" + dragData.DragString + "\" Dropped on layer list control, not on a layer",
              "SampleCsDragDrop",
              MessageBoxButtons.OK,
              MessageBoxIcon.Information
              );
              }
              else
              {
            MRhinoDoc doc = RhUtil.RhinoApp().ActiveDoc();
            if (null != doc && layerIndex < doc.m_layer_table.LayerCount())
            {
              MessageBox.Show(
            RhUtil.RhinoApp().MainWnd(),
            "String \"" + dragData.DragString + "\" Dropped on layer \"" + doc.m_layer_table[layerIndex].m_name + "\"",
            "SampleCsDragDrop",
            MessageBoxButtons.OK,
            MessageBoxIcon.Information
            );
            }
              }

              return true;
        }
Example #18
0
 private void copySelectedEntriesToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (SelectedEntries.Count == 0)
     return;
        StringBuilder csvText = new StringBuilder();
        StringBuilder rawText = new StringBuilder();
        DateTime sessionTime = (DateTime)filterSessionCombobox.SelectedItem;
        csvText.AppendLine(S._("Session: {0:F}", sessionTime));
        rawText.AppendLine(S._("Session: {0:F}", sessionTime));
        foreach (LogEntry entry in SelectedEntries.Values)
        {
     string timeStamp = entry.Timestamp.ToString("F", CultureInfo.CurrentCulture);
     string message = entry.Message;
     csvText.AppendFormat("\"{0}\",\"{1}\",\"{2}\"\n",
      timeStamp.Replace("\"", "\"\""), entry.Level.ToString(),
      message.Replace("\"", "\"\""));
     rawText.AppendFormat("{0}	{1}	{2}\n", timeStamp, entry.Level.ToString(),
      message);
        }
        if (csvText.Length > 0 || rawText.Length > 0)
        {
     DataObject tableText = new DataObject();
     tableText.SetText(rawText.ToString());
     byte[] bytes = Encoding.UTF8.GetBytes(csvText.ToString());
     MemoryStream tableStream = new MemoryStream(bytes);
     tableText.SetData(DataFormats.CommaSeparatedValue, tableStream);
     Clipboard.SetDataObject(tableText, true);
        }
 }
Example #19
0
        private void SETextBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (MouseButtons == MouseButtons.Left && !string.IsNullOrEmpty(_dragText))
            {
                Point pt = new Point(e.X, e.Y);
                int index = GetCharIndexFromPosition(pt);
                if (index >= _dragStartFrom && index <= _dragStartFrom + _dragText.Length)
                {
                    // re-make selection
                    SelectionStart = _dragStartFrom;
                    SelectionLength = _dragText.Length;

                    DataObject dataObject = new DataObject();
                    dataObject.SetText(_dragText, TextDataFormat.UnicodeText);
                    dataObject.SetText(_dragText, TextDataFormat.Text);

                    _dragFromThis = true;
                    if (Control.ModifierKeys == Keys.Control)
                    {
                        _dragRemoveOld = false;
                        DoDragDrop(dataObject, DragDropEffects.Copy);
                    }
                    else if (Control.ModifierKeys == Keys.None)
                    {
                        _dragRemoveOld = true;
                        DoDragDrop(dataObject, DragDropEffects.Move);
                    }
                }
            }
        }
Example #20
0
        protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e)
        {
            base.OnMouseMove(e);

            if (this.AllowDrag)
            {
                if (e.X < this.Width && e.Y < this.Height && e.X > 0 && e.Y > 0)
                {
                }
                else
                {
                    if (e.Button == System.Windows.Forms.MouseButtons.Left)
                    {
                        System.Windows.Forms.DataObject    data = new System.Windows.Forms.DataObject();
                        System.Windows.Forms.DragEventArgs de   =
                            new System.Windows.Forms.DragEventArgs(data,
                                                                   1,/*left mouse down*/
                                                                   e.X, e.Y,
                                                                   System.Windows.Forms.DragDropEffects.All,
                                                                   System.Windows.Forms.DragDropEffects.All);

                        OnDragStarting(this, de);
                        DoDragDrop(de.Data.GetData(data.GetFormats(false)[0]), System.Windows.Forms.DragDropEffects.All);
                        OnDragFinished(this, de);
                        //we there because need workaround of missing MouseUp after completing DoDragDrop
                        m_Pressed = false;
                        RefreshLayout();
                    }
                }
            }
        }
Example #21
0
		bool CopyTextToClipboard(string stringToCopy)
		{
			if (stringToCopy.Length > 0) {
				DataObject dataObject = new DataObject();
				dataObject.SetData(DataFormats.UnicodeText, true, stringToCopy);
				// Default has no highlighting, therefore we don't need RTF output
				if (textArea.Document.HighlightingStrategy.Name != "Default") {
					dataObject.SetData(DataFormats.Rtf, RtfWriter.GenerateRtf(textArea));
				}
				OnCopyText(new CopyTextEventArgs(stringToCopy));
				
				// Work around ExternalException bug. (SD2-426)
				// Best reproducable inside Virtual PC.
				// SetDataObject has "retry" parameters, but apparently a call to "DoEvents"
				// is necessary for the workaround to work.
				int i = 0;
				while (true) {
					try {
						Clipboard.SetDataObject(dataObject, true, 5, 50);
						return true;
					} catch (ExternalException) {
						if (i++ > 5)
							throw;
					}
					System.Threading.Thread.Sleep(50);
					Application.DoEvents();
					System.Threading.Thread.Sleep(50);
				}
			} else {
				return false;
			}
		}
Example #22
0
        public static bool CopyText(string text)
        {
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    IDataObject data = new DataObject();
                    string dataFormat;

                    if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 5)
                    {
                        dataFormat = DataFormats.Text;
                    }
                    else
                    {
                        dataFormat = DataFormats.UnicodeText;
                    }

                    data.SetData(dataFormat, false, text);
                    return CopyData(data);
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e, "Clipboard copy text failed.");
                }
            }

            return false;
        }
		bool CopyTextToClipboard(string stringToCopy, bool asLine)
		{
			if (stringToCopy.Length > 0) {
				DataObject dataObject = new DataObject();
				dataObject.SetData(DataFormats.UnicodeText, true, stringToCopy);
				if (asLine) {
					MemoryStream lineSelected = new MemoryStream(1);
					lineSelected.WriteByte(1);
					dataObject.SetData(LineSelectedType, false, lineSelected);
				}
				// Default has no highlighting, therefore we don't need RTF output
				if (textArea.Document.HighlightingStrategy.Name != "Default") {
					dataObject.SetData(DataFormats.Rtf, RtfWriter.GenerateRtf(textArea));
				}
				OnCopyText(new CopyTextEventArgs(stringToCopy));
				
				// Work around ExternalException bug. (SD2-426)
				// Best reproducable inside Virtual PC.
				try {
					Clipboard.SetDataObject(dataObject, true, 10, 50);
				} catch (ExternalException) {
					Application.DoEvents();
					try {
						Clipboard.SetDataObject(dataObject, true, 10, 50);
					} catch (ExternalException) {}
				}
				return true;
			} else {
				return false;
			}
		}
Example #24
0
        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*
            SceneJS scene = (SceneJS)treeView1.Nodes[0].Tag;
            if (scene != null)
            {
                object obj = scene.GetSelectedObject();
                if( obj != null )
                {
                    Clipboard.SetData("WebGLSceneObject", obj);
                }
            }
            */

            Clipboard.Clear();
            List<object> selected = new List<object>();
            foreach (TreeNode n in treeView1.SelectedNodes)
            {
                selected.Add(n.Tag);
            }

            DataFormats.Format df = DataFormats.GetFormat(typeof(List<object>).FullName);
            IDataObject dato = new DataObject();
            dato.SetData(df.Name, false, selected);

            Clipboard.SetDataObject(dato, false);
        }
        /// <summary>
        /// Copy selected text into Clipboard
        /// </summary>
        public static void Copy(FastColoredTextBox textbox)
        {
            if (textbox.Selection.IsEmpty)
            {
                textbox.Selection.Expand();
            }

            if (!textbox.Selection.IsEmpty)
            {
                var exp = new ExportToHTML();
                exp.UseBr = false;
                exp.UseNbsp = false;
                exp.UseStyleTag = true;
                string html = "<pre>" + exp.GetHtml(textbox.Selection.Clone()) + "</pre>";
                var data = new DataObject();
                data.SetData(DataFormats.UnicodeText, true, textbox.Selection.Text);
                data.SetData(DataFormats.Html, PrepareHtmlForClipboard(html));
                data.SetData(DataFormats.Rtf, new ExportToRTF().GetRtf(textbox.Selection.Clone()));
                //
                var thread = new Thread(() => SetClipboard(data));
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();
            }
        }
Example #26
0
 public void Copy()
 {
     IDataObject clips = new DataObject();
     clips.SetData(DataFormats.Bitmap, this.opened_image.get_bitmap());
     clips.SetData(DataFormats.Text, this.opened_image.get_file_name());
     Clipboard.SetDataObject(clips, true);
 }
        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            // gx2. jsx, jsc reflector
            // ?

            // http://support.microsoft.com/kb/307968

            // we can drag it into scite
            // DragDrop.DoDragDrop returns only after the complete drag-drop process is finished,
            // http://w3facility.org/question/dodragdrop-freezes-winforms-app-sometimes/
            // https://msdn.microsoft.com/en-us/library/ms649011(VS.85).aspx

            // http://www.codeproject.com/Articles/17266/Drag-and-Drop-Items-in-a-WPF-ListView

            Console.WriteLine("treeView1_ItemDrag"); ;

            // http://stackoverflow.com/questions/1772102/c-sharp-drag-and-drop-from-my-custom-app-to-notepad
            var x = new DataObject(
                "treeView1_ItemDrag " + new { e.Item }
            );


            // like props/ reg keys/ version nodes
            x.SetData("text/nodes/0", "hello");
            x.SetData("text/nodes/1", "world");

            // https://msdn.microsoft.com/en-us/library/system.windows.forms.control.dodragdrop(v=vs.110).aspx
            //this.DoDragDrop("treeView1_ItemDrag " + new { e.Item }, DragDropEffects.Copy);
            treeView1.DoDragDrop(x, DragDropEffects.Copy);

            // https://code.google.com/p/chromium/issues/detail?id=31037
            // https://searchcode.com/codesearch/view/32985148/
        }
Example #28
0
        public static void copyToClipboard(List<Frame> frames)
        {
            if (frames.Count == 0)
            {
                return;
            }

            DataObject data = new DataObject();
            data.SetData(frames.ToArray());

            if (frames.Count == 1)
            {
                // Not necessary, but Microsoft recommends that we should
                // place data on the clipboard in as many formats possible.
                data.SetData(frames[0]);
            }

            StringBuilder sb = new StringBuilder();
            foreach (Frame frame in frames)
            {
                sb.AppendLine(frame.getTabSeparatedString());
            }
            data.SetText(sb.ToString());

            Clipboard.SetDataObject(data, true);
        }
Example #29
0
 public static bool CopyTextToClipboard(string stringToCopy)
 {
     if (stringToCopy.Length > 0)
     {   
         DataObject dataObject = new DataObject();
         dataObject.SetData(DataFormats.UnicodeText, true, stringToCopy);
         // Work around ExternalException bug. (SD2-426)
         // Best reproducable inside Virtual PC.
         try
         {
             Clipboard.SetDataObject(dataObject, true, 10, 50);
         }
         catch (ExternalException)
         {
             Application.DoEvents();
             try
             {
                 Clipboard.SetDataObject(dataObject, true, 10, 50);
             }
             catch (ExternalException) { }
         }
         return true;
     }
     else
     {
         return false;
     }
 }
Example #30
0
        static void Main(string[] args)
        {
            //// Excel Spreadsheet example
            //GetExcelSpreadsheet();
            //PasteExcelSpreadsheet();


            var currentData = Clipboard.GetDataObject();
            var newData     = new System.Windows.Forms.DataObject();

            // Go through all the formats in the clipboard, and only copy
            // the formats selected with CopyDataFromCurrentToNew().
            // All other formats will be removed from the clipboard.
            foreach (string format in currentData.GetFormats())
            {
                // Sometimes CF_BITMAP show as a zero length content,
                // but Handle Type is bitmap, which apparently is treated differently.
                // Is there really an image in the clipboard?
                Console.WriteLine(format);
                if (format == "Bitmap")
                {
                    var bitmap = currentData.GetData(format) as System.Drawing.Bitmap;
                    Console.WriteLine("{0}x{1}", bitmap.Width, bitmap.Height);
                }

                //CopyDataFromCurrentToNew(currentData, newData, format, "CF_UNICODETEXT");
                CopyDataFromCurrentToNew(currentData, newData, format, "PNG");
            }

            Clipboard.SetDataObject(newData, true);
        }
        public void CopyAsCodeBlock()
        {
            //{\rtf\ansi{\fonttbl{\f0 Cousine;}}{\colortbl;\red0\green0\blue255;}\f0 \fs18        \cf1 void\cf0  test()\par         \{\par             \cf1 int\cf0  i = 0; \par         \}\par }

            // Change selection starting point by removing white space
            int leftWhiteSpaceCount = _selection.Text.Length - _selection.Text.TrimStart(' ').Length;
            _selection.MoveToLineAndOffset(_selection.TopPoint.Line, _selection.TopPoint.DisplayColumn + leftWhiteSpaceCount, true);

            //SendKeys.SendWait("^(c)");  // copy selected
            _selection.Copy();

            DataObject dataObject = (DataObject)Clipboard.GetDataObject();
            DataObject newDataObject = new DataObject();

            // clear text
            string text = dataObject.GetText();

            int len = text.Length;
            text = text.TrimStart(null);
            int firstLineStartIndex = text.Length - text.TrimStart(null).Length;
            int secondLineStartIndex = firstLineStartIndex + 8;

            var sb = new StringBuilder();

            string[] lines = text.Split(new[] { "\r\n" }, StringSplitOptions.None);
            sb.AppendLine(lines[0].TrimStart(' '));
            for (var i = 1; i < lines.Length; i++)
            {
                sb.AppendLine(lines[i].Substring(secondLineStartIndex));
            }

            newDataObject.SetText(sb.ToString());
            sb.Clear();

            // rich text
            string rtf = (string)dataObject.GetData(DataFormats.Rtf);

            // change font
            rtf = rtf.Replace(@"{\fonttbl{\f0 Cousine;}}", @"{\fonttbl{\f0 Consolas;}}");

            string[] rtfLines = rtf.Split(new[] { @"\par " }, StringSplitOptions.None);

            sb.AppendLine(rtfLines[0]);
            for (var i = 1; i < rtfLines.Length; i++)
            {
                sb.Append(@"\par ");
                if (rtfLines[i].Length > secondLineStartIndex)
                {
                    sb.Append(rtfLines[i].Substring(secondLineStartIndex));
                }
                else
                {
                    sb.Append(rtfLines[i]);
                }
            }
            newDataObject.SetData(DataFormats.Rtf, sb.ToString());

            Clipboard.SetDataObject(newDataObject);
        }
Example #32
0
 private void button1_Click(object sender, EventArgs e)
 {
     DateTime epoch = new DateTime(1970, 1, 1);
     long timestamp = (dateTimePicker1.Value.ToUniversalTime().Ticks - epoch.Ticks) / TimeSpan.TicksPerSecond;
     IDataObject dataObject = new DataObject("Text", textBox2.Text);
     dataObject.SetData("SkypeMessageFragment", new MemoryStream(Encoding.UTF8.GetBytes(String.Format("<quote author=\"{0}\" timestamp=\"{1}\">{2}</quote>", textBox1.Text, timestamp, textBox2.Text))));
     Clipboard.SetDataObject(dataObject);
 }
Example #33
0
 /// <summary>
 /// Get data object with given html and plaintext ready to be used for clipboard or drag & drop.
 /// </summary>
 /// <param name="html">a html fragment</param>
 /// <param name="plainText">the plain text</param>
 public static DataObject GetDataObject(string html, string plainText)
 {
     var data = GetHtmlData(html);
     var dataObject = new DataObject();
     dataObject.SetData(DataFormats.Html, data);
     dataObject.SetData(DataFormats.Text, plainText);
     return dataObject;
 }
Example #34
0
		public static void CopyUrl(string url, string name = null)
		{
			var dto = new DataObject(DataFormats.Html, string.Format(_htmlTemplate, url));
			dto.SetData(DataFormats.Text, url);
			if (!string.IsNullOrEmpty(name))
				dto.SetData(MessageSubjectFormat, name);
			Clipboard.SetDataObject(dto);
		}
 private void lbl_drag_plain_MouseDown(object sender, MouseEventArgs e)
 {
     DataObject data = new DataObject();
     var ana= new Person() {Name = "Ana", Age = 56 };
     var json_stringAna = JObject.FromObject(ana).ToString();
     data.SetText(json_stringAna, TextDataFormat.Text);
     lbl_drag_plain.DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Move);
 }
Example #36
0
 private void button1_Click(object sender, EventArgs e)
 {
     DataObject data = new DataObject();
     data.SetData(DataFormats.Text, textBox1.Text);
     string html = "<p>" + textBox1.Text + "</p>";
     data.SetData(DataFormats.Html, html);
     Clipboard.SetDataObject(data, true);
 }
Example #37
0
        private void copyLocationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IDataObject       ido = new System.Windows.Forms.DataObject();
            ClipboardLocation loc = new ClipboardLocation(Convert.ToInt32(LastMouseVector.X), Convert.ToInt32(LastMouseVector.Y), RegionMgr.CurrentRegion.ID);

            ido.SetData(loc);
            Clipboard.SetDataObject(ido, true);
        }
Example #38
0
        protected override void Work()
        {
            var obj = new System.Windows.Forms.DataObject(
                _format,
                _data
                );

            Clipboard.SetDataObject(obj, true);
        }
Example #39
0
 private void copyToolStripMenuItem_Click(object sender, EventArgs e)
 {
     // Ctrl + C should preform this as well, so there is no need to override ProcessCmdKey.
     MemoryStream ms = new MemoryStream();
     textureDisplay.Image.Save(ms, ImageFormat.Png);
     IDataObject dataObject = new DataObject();
     dataObject.SetData("PNG", false, ms);
     Clipboard.SetDataObject(dataObject, true);
 }
Example #40
0
        private void CopySelectedGrab(object sender, ExecutedRoutedEventArgs e)
        {
            var         imgdata = SelectedCapture.ImageAsJpg();
            Image       img     = Image.FromStream(imgdata);
            IDataObject dataObj = new DataObject();

            dataObj.SetData(img);
            WpfClipboard.SetClipboardDataObject(dataObj);
        }
Example #41
0
        public static void CopyCtrl2ClipBoard(Control ctrl)
        {
            CBFormCtrl  cbCtrl = new CBFormCtrl(ctrl);
            IDataObject ido    = new System.Windows.Forms.DataObject();

            //ido.SetData(CBFormCtrl.Format.Name, true, cbCtrl);
            //ido = Clipboard.GetDataObject();
            ido.SetData(CBFormCtrl.Format.Name, false, cbCtrl);
            Clipboard.SetDataObject(ido, false);
        }
Example #42
0
        public DataObject GetDataObject()
        {
            DataObject ret = new System.Windows.Forms.DataObject();
            foreach (String format in _dict.Keys)
            {
                ret.SetData(format, _dict[format]);
            }

            return ret;
        }
Example #43
0
        private void CopyAlltoClipboard(DataGridView dgv)
        {
            dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
            dgv.SelectAll();
            System.Windows.Forms.DataObject dataObj = dgv.GetClipboardContent();

            if (dataObj != null)
            {
                Clipboard.SetDataObject(dataObj);
            }
        }
Example #44
0
 private void KTreeView_MouseMove(object sender, MouseEventArgs e)
 {
     if ((this.igxObject_0 != null) && ((e.Button & MouseButtons.Left) == MouseButtons.Left))
     {
         this.point_0 = SystemInformation.WorkingArea.Location;
         System.Windows.Forms.DataObject data = new System.Windows.Forms.DataObject();
         data.SetData(this.arrayList_0);
         base.DoDragDrop(data,
                         DragDropEffects.Link | DragDropEffects.Move | DragDropEffects.Copy | DragDropEffects.Scroll);
     }
 }
Example #45
0
 private void copyAlltoClipboard()
 {
     dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
     dataGridView1.MultiSelect       = true;
     dataGridView1.SelectAll();
     System.Windows.Forms.DataObject dataObj = dataGridView1.GetClipboardContent();
     if (dataObj != null)
     {
         System.Windows.Forms.Clipboard.SetDataObject(dataObj);
     }
 }
        private DragEventArgs Given_DraggedText()
        {
            var dObject = new DataObject(
                DataFormats.UnicodeText,
                "hello world");

            return(new DragEventArgs(
                       dObject, 0, 40, 40,
                       (System.Windows.Forms.DragDropEffects)(int) DragDropEffects.All,
                       (System.Windows.Forms.DragDropEffects)(int) DragDropEffects.All));
        }
Example #47
0
 /// <summary>
 /// Handle clipboard changes.
 /// </summary>
 /// <param name="data"></param>
 /// <param name="formats"></param>
 void ClipboardMonitor_OnClipboardChange(System.Windows.Forms.DataObject data, string[] formats)
 {
     System.Windows.Application.Current.Dispatcher.Invoke(
         System.Windows.Threading.DispatcherPriority.Normal,
         (Action) delegate()
     {
         CopyItem it;
         it = new CopyItem(data, formats);
         AddToList(it);
     });
 }
Example #48
0
        private DragEventArgs Given_DraggedText()
        {
            var dObject = new DataObject(
                DataFormats.UnicodeText,
                "hello world");

            return(new DragEventArgs(
                       dObject, 0, 40, 40,
                       DragDropEffects.All,
                       DragDropEffects.All));
        }
        private Reko.Gui.Controls.DragEventArgs Given_DraggedFile()
        {
            var dObject = new DataObject(
                DataFormats.FileDrop,
                "/home/bob/foo.exe");

            return(new Reko.Gui.Controls.DragEventArgs(
                       dObject, 0, 40, 40,
                       Reko.Gui.Controls.DragDropEffects.All,
                       Reko.Gui.Controls.DragDropEffects.All));
        }
Example #50
0
        /// <summary>
        /// 测试生成RTF文档并设置到系统剪切板中
        /// 执行这个函数后就可以在 MS Word中使用粘贴操作来显示程序生成的文档了
        /// </summary>
        internal static void TestClipboard()
        {
            System.IO.StringWriter myStr = new System.IO.StringWriter();
            RTFWriter w = new RTFWriter(myStr);

            TestBuildRTF(w);
            w.Close();
            System.Windows.Forms.DataObject data = new System.Windows.Forms.DataObject();
            data.SetData(System.Windows.Forms.DataFormats.Rtf, myStr.ToString());
            System.Windows.Forms.Clipboard.SetDataObject(data, true);
            System.Windows.Forms.MessageBox.Show("好了,你可以在MS Word 中粘贴文本了.");
        }
Example #51
0
        private void Copy_Click(object sender, RoutedEventArgs e)
        {
            var    data = new System.Windows.Forms.DataObject();
            Thread thread;

            data.SetData(System.Windows.Forms.DataFormats.UnicodeText, true, RecordText.Text);
            thread = new Thread(() => System.Windows.Forms.Clipboard.SetDataObject(data, true));
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            System.Windows.Forms.MessageBox.Show("Скопировано");
        }
Example #52
0
 public void Copy(ClipboardContentType type, object contents)
 {
     System.Windows.Forms.IDataObject data = new System.Windows.Forms.DataObject(this.GetDataFormatByContentType(type), contents);
     if (type == ClipboardContentType.FileDrop)
     {
         MemoryStream stream = new MemoryStream(4);
         byte[]       bytes  = new byte[] { 5, 0, 0, 0 };
         stream.Write(bytes, 0, bytes.Length);
         data.SetData("Preferred DropEffect", stream);
     }
     this.Contents = data;
 }
Example #53
0
        //拖动到这个房间的完成
        public void personDragDrop(object sender, DragEventArgs e)
        {
            //  e.Effect = DragDropEffects.Move;
            Button button = sender as Button;

            System.Windows.Forms.DataObject ido = e.Data as System.Windows.Forms.DataObject;

            Person person = new Person();

            person = ido.GetData(person.GetType()) as Person;

            // MessageBox.Show(person.getNoteName(), "测试");
        }
Example #54
0
        /// <summary>
        /// Sets managed data to a clipboard DataObject.
        /// </summary>
        /// <param name="dataObject">The DataObject to set the data on.</param>
        /// <param name="format">The clipboard format.</param>
        /// <param name="data">The data object.</param>
        /// <remarks>
        /// Because the underlying data store is not storing managed objects, but
        /// unmanaged ones, this function provides intelligent conversion, allowing
        /// you to set unmanaged data into the COM implemented IDataObject.</remarks>
        public static void SetDataEx(this System.Windows.Forms.IDataObject dataObject, string format, object data)
        {
            DataFormats.Format dataFormat = DataFormats.GetFormat(format);

            // Initialize the format structure
            var formatETC = new FORMATETC();

            formatETC.cfFormat = (short)dataFormat.Id;
            formatETC.dwAspect = DVASPECT.DVASPECT_CONTENT;
            formatETC.lindex   = -1;
            formatETC.ptd      = IntPtr.Zero;

            // Try to discover the TYMED from the format and data
            TYMED tymed = GetCompatibleTymed(format, data);

            // If a TYMED was found, we can use the system DataObject
            // to convert our value for us.
            if (tymed != TYMED.TYMED_NULL)
            {
                formatETC.tymed = tymed;

                // Set data on an empty DataObject instance
                var conv = new System.Windows.Forms.DataObject();
                conv.SetData(format, true, data);

                // Now retrieve the data, using the COM interface.
                // This will perform a managed to unmanaged conversion for us.
                STGMEDIUM medium;
                ((IDataObject)conv).GetData(ref formatETC, out medium);
                try {
                    // Now set the data on our data object
                    ((IDataObject)dataObject).SetData(ref formatETC, ref medium, true);
                }
                catch {
                    // On exceptions, release the medium
                    ReleaseStgMedium(ref medium);
                    throw;
                }
            }
            else
            {
                // Since we couldn't determine a TYMED, this data
                // is likely custom managed data, and won't be used
                // by unmanaged code, so we'll use our custom marshaling
                // implemented by our COM IDataObject extensions.

                ((IDataObject)dataObject).SetManagedData(format, data);
            }
        }
Example #55
0
 public bool Copy()
 {
     if (myImage == null)
     {
         return(false);
     }
     System.Windows.Forms.DataObject d   = new System.Windows.Forms.DataObject();
     System.Drawing.Bitmap           bmp = this.GetSelectedBmp();
     if (bmp == null)
     {
         bmp = new System.Drawing.Bitmap(this.myImage);
     }
     d.SetData(System.Windows.Forms.DataFormats.Bitmap, bmp);
     System.Windows.Forms.Clipboard.SetDataObject(d);
     return(true);
 }
Example #56
0
        /// <summary>
        /// Adds the specified data to the clipboard
        /// </summary>
        public static void AddToClipboard(params ClipboardData[] data)
        {
            Forms.IDataObject dataObject = new Forms.DataObject();
            foreach (var clipboardData in data)
            {
                if (clipboardData.Data != null)
                {
                    dataObject.SetData(Clipboard.FormatToString(clipboardData.Format), clipboardData.Data);
                }
            }

            if (dataObject.GetFormats().Length > 1)
            {
                Forms.Clipboard.SetDataObject(dataObject, copy: true);
            }
        }
Example #57
0
 ///<Summary>Constructor starting with a .Net Data object
 /// .Net DataObjects are easy to work with, but are useless
 /// if the Dragged items are non-FileSystem
 /// The DragWrapper class will never call this.
 /// It is here for playing around with the CDragWrapper class
 /// </Summary>
 public CProcDataObject(System.Windows.Forms.DataObject NetObject)
 {
     NetIDO = NetObject;
     ProcessNetDataObject(NetObject);
     if (m_IsValid)
     {
         try
         {
             m_DataObject = Marshal.GetComInterfaceForObject(NetObject, Type.GetTypeFromCLSID(new Guid("0000010e-0000-0000-C000-000000000046"), true));
         }
         catch (Exception ex)
         {
             Debug.WriteLine("Failed to get COM IDataObject:" + ex.ToString());
             m_DataObject = IntPtr.Zero;
             m_Draglist   = new ArrayList();                   //let GC clean em up
             m_IsValid    = false;
         }
     }
 }
Example #58
0
        private void SetData(object data, string format)
        {
            object obj = new DataContainer(data);

            if (string.IsNullOrEmpty(format))
            {
                // Create a dummy DataObject object to retrieve all possible formats.
                // Ex.: For a System.String type, GetFormats returns 3 formats:
                // "System.String", "UnicodeText" and "Text"
                System.Windows.Forms.DataObject dataObject = new System.Windows.Forms.DataObject(data);
                foreach (string fmt in dataObject.GetFormats())
                {
                    _Data[fmt] = obj;
                }
            }
            else
            {
                _Data[format] = obj;
            }
        }
Example #59
0
        public void Paste(ClipItem clip)
        {
            switch (clip.Type)
            {
            case ClipItem.EType.eText:
            {
                fLocalCopy = true;
                DataObject data = new DataObject();
                data.SetData(DataFormats.Text, clip.Content);
                Clipboard.Clear();
                Clipboard.SetDataObject(data);
                if (fCallFromHotkey)
                {
                    fCallFromHotkey = false;
                    Hide();
                    SendKeys.SendWait("^v");
                }
                break;
            }

            case ClipItem.EType.eImage:
            {
                fLocalCopy = true;
                DataObject data = new DataObject();
                data.SetData(DataFormats.Bitmap, clip.Image);
                Clipboard.Clear();
                Clipboard.SetDataObject(data);
                if (fCallFromHotkey)
                {
                    fCallFromHotkey = false;
                    Hide();
                    SendKeys.SendWait("^v");
                }
                break;
            }

            default:
                break;
            }
        }
Example #60
0
        public static TransferDataSource ToXwt(this SWF.DataObject data)
        {
            var result = new TransferDataSource();

            result.DataRequestCallback = dt => data.GetData(dt.ToSwf());

            foreach (var item in data.GetFormats())
            {
                var format = ToXwtTransferType(item);
                if (format == TransferDataType.Uri)
                {
                    result.DataRequestCallback = dt => {
                        var value = data.GetData(TransferDataType.Uri.ToSwf());
                        var uris  = ((string[])value).Select(f => new Uri(f)).ToArray();
                        return(uris);
                    };
                }
                result.AddType(format);
            }

            return(result);
        }