views:

679

answers:

2

Hi,

I found that code somewhere and I find it quite useful but I would like to find a way to make it work so it capture only the given window target. Maybe with a processID or Window Name. Even if that window is not active.

I do not want to make that window active but want to get a screen capture like if I was doing Alt+PrintScreen on it.

Here is the code that works for full Screen Capture

    Private bmpScreenShot As Bitmap
    Private gfxScreenshot As Graphics

    bmpScreenShot = New Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb)

    gfxScreenshot = Graphics.FromImage(bmpScreenShot)
    gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy)

    bmpScreenShot.Save(fileName, ImageFormat.Png)

I use the Visual Basic 2008 Express

Thank you in advance!

+1  A: 

Look at this http://stackoverflow.com/questions/1163761/c-capture-screenshot-of-active-window Instead of this.Handle (current window) you may insert a handle of any other window (using WinAPI functions like FindWindow)

Nagg
A: 

Hi. I found the code below somewhere. Working well except that it doesnt work when the window isnt active. Any idea how to make it work on Foreground window?

Here is the code I used :

    Public Function CaptureWindow(ByVal handle As IntPtr) As Image
        Dim hdcSrc As IntPtr = User32.GetWindowDC(handle)
        Dim windowRect As User32.RECT = New User32.RECT()
        User32.GetWindowRect(handle, windowRect)
        Dim width As Integer = windowRect.right - windowRect.left
        Dim height As Integer = windowRect.bottom - windowRect.top
        Dim hdcDest As IntPtr = GDI32.CreateCompatibleDC(hdcSrc)
        Dim hBitmap As IntPtr = GDI32.CreateCompatibleBitmap(hdcSrc, width, height)
        Dim hOld As IntPtr = GDI32.SelectObject(hdcDest, hBitmap)
        GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, _
         0, 0, GDI32.SRCCOPY)
        GDI32.SelectObject(hdcDest, hOld)
        GDI32.DeleteDC(hdcDest)
        User32.ReleaseDC(handle, hdcSrc)
        Dim img As Image = Image.FromHbitmap(hBitmap)
        GDI32.DeleteObject(hBitmap)
        Return img
    End Function

    Dim clientHwnd As New IntPtr(0)
    clientHwnd = FindWindow(Nothing, "Calculatrice")

    If (clientHwnd.ToString <> "0") Then
        Dim img As Image = CaptureWindow(clientHwnd)
        Picturebox1.Image = img
    End If
Steve Thomas
Try to use IntPtr GetForegroundWindow() function (returns foregrround window hwnd)
Nagg
Yep I tried. Thats even worst. Without the GetForegroundWindow I could atleast capture the Calculator even if that window wasnt active. But it had to be on top of everything.Maybe I forgot to mention that I want to be able to capture a window that could be hidden behind another one.Thank you for your answer though!
Steve Thomas