Search code examples
c#screen-capture

Capture Screen But Not Current Form In C#?


I want to capture the screen but without the current form, I tried to minimize -> capture -> maximize, but I'm looking for a better solution if exists. This was my code::

    int w = this.Width;
    int h = this.Height;
    Size sz = this.Size;
    Point loc = this.Location;

    this.WindowState = FormWindowState.Minimized;

    System.Threading.Thread.Sleep(500);

    using (Bitmap b = new Bitmap(w, h))
    {
        using (Graphics g = Graphics.FromImage(b))
        {
            g.CopyFromScreen(loc, new Point(0, 0), sz);
        }

        b.Save(Environment.CurrentDirectory + "\\slides\\screen.jpeg");

        this.BackgroundImage = System.Drawing.Image.FromFile(@"slides\screen.jpeg");
    }

    this.WindowState = FormWindowState.Maximized;

And I ask if there is a direct way to put the captured image as form background, without saving it.


Solution

  • Try, although I did notice both yours and mine is marginally offset by the form border.

        int w = this.Width; 
        int h = this.Height; 
        Size sz = this.Size; 
        Point loc = this.Location; 
        Hide();
        System.Threading.Thread.Sleep(500);
        using (Image b = new Bitmap(w, h)) 
        { using (Graphics g = Graphics.FromImage(b)) 
        { 
            g.CopyFromScreen(loc, new Point(0, 0), sz); }
    
            Image x = new Bitmap(b);
            this.BackgroundImage = x;
        } 
        Show();