Capture image of App#A's window from App#B

Capture image of App#A's window from App#B

Post by RnJlZGVyaW » Sun, 26 Apr 2009 23:12:01

How can I capture (an image) of the contents of Application #A window ...
from Application #B. Let's say there are two, totally separate, independent
applications running, #A & #B. From Application #B, I want to locate
Application #A, then locate #A's currently active desktop window and capture
an image of whatever's being shown.

Application #A - I have no idea what programming method/tools were used to
create this app

Application #B (the imager capturer) - will be written using the .NET CLR
and either C# or VB.NET in a Winforms Applications.

Any pointers or help appreciated.


Capture image of App#A's window from App#B

Post by Armin Zing » Mon, 27 Apr 2009 02:23:44

If you can live with the limitation of capturing the "main window", see the
following example. Otherwise: you have to use p/Invoke (EnumWindows). Inside
the callback function, call GetWindowThreadProcessId to find out if the
window belongs to the process in question.

(no error checking inside...!)

<Runtime.InteropServices.StructLayout( _
Runtime.InteropServices.LayoutKind.Sequential)> _
Structure RECT
Public left, top, right, bottom As Int32

Public ReadOnly Property Width() As Int32
Return right - left
End Get
End Property
Public ReadOnly Property Height() As Int32
Return bottom - top
End Get
End Property
Public ReadOnly Property Size() As Size
Return New Size(Width, Height)
End Get
End Property
End Structure

Declare Function GetWindowRect Lib "user32.dll" ( _
ByVal hwnd As IntPtr, ByRef Rect As RECT) As Boolean

Private Shared Function CaptureProcessMainWindow( _
ByVal ProcessName As String) As Bitmap

Dim p = Process.GetProcessesByName(ProcessName)
Dim hwnd = p(0).MainWindowHandle
Dim rect As RECT

If GetWindowRect(hwnd, rect) Then
Dim bmp As New Bitmap(rect.Width, rect.Height)

Using g = Graphics.FromImage(bmp)
g.CopyFromScreen(rect.left,, 0, 0, rect.Size)
End Using

Return bmp
Return Nothing
End If

End Function

Be aware that the window must be fully visible because the function captures
a part of the screen.