-1

I'm using WinForms. I'm have 2 forms. In form1 i have a picturebox and in form2 i have a button that prints. I'm trying to build an application that will print the images from the picturebox in Form1 using Form2.

I first tried making a panel and testing if the pictures would print in form1, and it did, but the problem is when copied the printing code to form2, the code wouldn't let me access the picturebox in form1.

How do i access the picturebox in Form1 from Form2 so i cant print the images in the picturebox.

I receive error lines under this.pictureBox1.

Form2

    private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
       var bmp = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);
       this.pictureBox1.DrawToBitmap(bmp, this.pictureBox1.ClientRectangle);
       e.Graphics.DrawImage(bmp, 25, 25, 800, 1050);
    }

2 Answers2

3

You can make your PictureBox from Form1 available to Form2 by passing a reference to it as a property.

I'm not sure how you have your forms set up for loading. But if you are using a Main form that manages Form1 and Form2 you can do something like the following. If you do not have a Main form then this should at least get you on the right track.

Form1

public PictureBox ThePicture
{
    get {return this.pictureBox1; }
}

Form2

private PictureBox _thePicture;
public PictureBox ThePicture
{
    set { this._thePicture = value; }
    get { return this._thePicture; }
}

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
   if (this.ThePicture != null)
   {
       var bmp = new Bitmap(this.ThePicture.Width, this.ThePicture.Height);
       this.ThePicture.DrawToBitmap(bmp, this.ThePicture.ClientRectangle);
       e.Graphics.DrawImage(bmp, 25, 25, 800, 1050);
   }
}

Main Form

Form1 form1 = new Form1();
Form2 form2 = new Form2();
form2.ThePicture = form1.ThePicture;
Darren H
  • 450
  • 3
  • 5
  • In var bmp = new Bitmap(this.ThePicture.Width, this.ThePicture.Height); I keep getting on this.ThePicture i get red error lines. The property or indexer 'PrinterForm.ThePicture' cannot be used in this context because it lacks the get accessor – Learning_To_Code Oct 28 '15 at 18:17
  • Ah, right, I added the missing GET to Form2 ThePicture. You could also just reference the _thePicture variable directly from within printDocument1_PrintPage. Example: `var bmp = new Bitmap(this._thePicture.Width, this._thePicture.Height);` – Darren H Oct 28 '15 at 19:17
0

Try to do so:

//Tente fazer assim:
public Form1()
    {
        InitializeComponent();
    }

    public Image getImagePic
    {
        get 
        {
            return this.pictureBox1.Image;
        }

    }
Ripke
  • 1
  • 1