Home > other >  Get and Set Image to Picturebox when Image was creating in other class
Get and Set Image to Picturebox when Image was creating in other class

Time:11-24

im trying to learn everyday something new about c#. Now im trying to get Image from Desktop and I did it in another class. Now i dont know how this is gonna work. How can i get the image which was created in my screenshot.cs so that i can set it to picturebox which is in my Form1.cs

My Code is this:

namespace CatchAreaToImage
{

    public partial class Form1 : Form
    {

        Bitmap screen;

          
        public Form1()
        {

            InitializeComponent();
        }
        Bitmap screen2;
        private void button1_Click(object sender, EventArgs e)
        {
            Screenshot.CaptureScreen(screen2);

            pBArea.Image = screen2;


        }

My Screenshot.cs ist this:

    class Screenshot
    {

        public static void CaptureScreen() //do screenshot of desktop
        {
            // Take an image from the screen
            Bitmap screen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); // Create an empty bitmap with the size of the current screen 

            Graphics graphics = Graphics.FromImage(screen as Image); // Create a new graphics objects that can capture the screen

            graphics.CopyFromScreen(0, 0, 0, 0, screen.Size); // Screenshot moment → screen content to graphics object

        }

    }
        public void Image(Bitmap screen)
        {
            screen2 = screen;
        }

I hope i could describe my problem correctly.

CodePudding user response:

You can modify your CaptureScreen method to return the Bitmap variable screen and assign it to pictureBox.Image property.

class Screenshot
{
    public static Image CaptureScreen()
    {
        
        Bitmap screen = new Bitmap(
            Screen.PrimaryScreen.Bounds.Width, 
            Screen.PrimaryScreen.Bounds.Height);

        Graphics graphics = Graphics.FromImage(screen as Image);

        graphics.CopyFromScreen(0, 0, 0, 0, screen.Size); 

        return screen;
    }
}

And then in form class you can do assignment as the Bitmap inherits from Image

namespace CatchAreaToImage
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Image screen = Screenshot.CaptureScreen(); 
            this.pictureBox1.Image = screen;
            // other uses of screen possible
        }
    }
}
  • Related