c# screenshot of active window but doesn't caputre the window

5.5k Views Asked by At

I'm creating an application in which I need to create a PDF file with the screenshot of the application.

I found how to create the screenshot and how to put it in my file. All is working well in most situations.

My problem comes when I use more than one screen or a programm like Teamviewer. The problem is, my programm captures the right area (good coordinates on the screen whenever which screen) but it captures all what's behind the window but not the window.

Does somebody knows what am I doing wrong or if I missed a detail ?

Here is the code I'm currently using :

// creates an rectangle of the size of the window
        Rectangle bounds = new Rectangle(
            (int)System.Windows.Application.Current.MainWindow.Left+10, 
            (int)System.Windows.Application.Current.MainWindow.Top+10, 
            (int)System.Windows.Application.Current.MainWindow.Width-20, 
            (int)System.Windows.Application.Current.MainWindow.Height-20);

        // creates a bitmap with a screenshot of the size of the window
        Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
        Graphics g = Graphics.FromImage(bitmap);
        g.CopyFromScreen(new System.Drawing.Point(bounds.Left, bounds.Top), new System.Drawing.Point(0,0), bounds.Size);

Thanks in advance for any help or examples.

1

There are 1 best solutions below

0
On

I don't understand exactly you. I think you need to do is capture the active window.

Rectangle bounds = Screen.GetBounds(Point.Empty);
using(Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
    using(Graphics g = Graphics.FromImage(bitmap))
    {
         g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
    }
    bitmap.Save("test.jpg", ImageFormat.Jpeg);
}

//for capturing current window use

 Rectangle bounds = this.Bounds;
 using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
 {
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.CopyFromScreen(new Point(bounds.Left,bounds.Top), Point.Empty, bounds.Size);
    }
    bitmap.Save("C://test.jpg", ImageFormat.Jpeg);
 }

Source: Capture screenshot of active window?