NullReferenceException in copy / paste image

I am getting an error implementing this simple code. I do not understand where I am mistaken.

//MISTAKE

An unhandled exception of type "System.NullReferenceException" occurred in ImageCSharp.exe
Further information: Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.

I can get the clipboard text, but why can't I get / set the image.

// CODE

public void copy() { // Determine the active child form. fImage activeChild = this.ActiveMdiChild as fImage; if (activeChild != null) { PictureBox mypicbox = activeChild.picbox; string win_name = activeChild.Tag.ToString(); Clipboard.SetImage(mypicbox.Image); Clipboard.SetText(win_name); } } private void paste() { Image im= Clipboard.GetImage(); this.pictureBox1.Image = im; MessageBox.Show(im.Size.ToString()); } 

Yours faithfully,

0
c #
source share
2 answers
  Clipboard.SetText(win_name); 

Resets the image from the clipboard, it can contain only one element. Delete the line to solve your problem. And protect the code:

  private void paste() { if (Clipboard.ContainsImage()) { Image im = Clipboard.GetImage(); if (this.pictureBox1.Image != null) this.pictureBox1.Dispose(); this.pictureBox1.Image = im; } } 

To get both pieces of information on the clipboard, first declare a small helper class to hold this information. For example:

  [Serializable] private class Clipdata { public Image Image { get; set; } public string Name { get; set; } } private void CopyButton_Click(object sender, EventArgs e) { var data = new Clipdata { Image = pictureBox1.Image, Name = textBox1.Text }; Clipboard.SetDataObject(data); } private void PasteButton_Click(object sender, EventArgs e) { string fmt = typeof(Clipdata).FullName; if (Clipboard.ContainsData(fmt)) { var data = (Clipdata)Clipboard.GetDataObject().GetData(fmt); if (pictureBox1.Image != null) pictureBox1.Image.Dispose(); pictureBox1.Image = data.Image; textBox1.Text = data.Name; } } 
+1
source share

Not the answer to your question, but the next one will not set the image as well as the text to the clipboard. those. your code will set the text to the clipboard

 Clipboard.SetImage(mypicbox.Image); Clipboard.SetText(win_name); 

The above code tries to set the image to the clipboard, and then the text.
that is, the clipboard will contain one element, which is the text according to your code.

And I suppose, because of this, the code inside paste , which expects the image to be on the clipboard, throws an exception on MessageBox.Show(img.Size.ToString()); .

+1
source share

All Articles