views:

5894

answers:

4

I am making a screen capturing application and everything is going fine. All I need to do is capture the active window and take a screenshot of this active window. Does anyone know how I can do this?

+14  A: 
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);
 }
ArsenMkrt
Neat! I though you would have to use the WinAPI. Do you know if this is implemented on Mono?
Lucas Jones
I didn't try it for mono, but it works fine in framework
ArsenMkrt
This just gives me a normal screenshot. Don't I have to use the WinAPI?
Nate Shoffner
downvoter please leave a comment... I edited the post now you can capture current window too
ArsenMkrt
+1  A: 

You can use the code from this question: http://stackoverflow.com/questions/158151/how-can-i-save-screenshot-directly-to-a-file-in-windows

Just change WIN32_API.GetDesktopWindow() to the Handle property of the window you want to capture.

Richard Szalay
+4  A: 
ScreenCapture sc = new ScreenCapture();
// capture entire screen, and save it to a file
Image img = sc.CaptureScreen();
// display image in a Picture control named imageDisplay
this.imageDisplay.Image = img;
// capture this window, and save it
sc.CaptureWindowToFile(this.Handle,"C:\\temp2.gif",ImageFormat.Gif);

http://www.developerfusion.com/code/4630/capture-a-screen-shot/

joe
I already know how to capture a standard screenshot. I just need to know how to capture the active window.
Nate Shoffner
i have changed information
joe
+2  A: 

I assume you use Graphics.CopyFromScreen to get the screenshot.

You can use P/Invoke to GetForegroundWindow (and then get its position and size) to determine which region you need to copy from.

modosansreves