@mcp.tool()
def screenshot_window(target: Union[str, int], save_path: str = "") -> Dict[str, Any]:
"""
Take a screenshot of a specific window.
Args:
target: Window title (string) or HWND handle (integer)
save_path: Optional path to save the screenshot (PNG). If empty, returns base64.
Returns:
Screenshot info with base64 data or saved file path.
"""
if not SCREENSHOT_AVAILABLE:
return {"error": "Screenshot support not available. Install: pip install pywin32 pillow"}
try:
# Find the window
hwnd = None
if isinstance(target, int):
hwnd = target
else:
def find_window(h, _):
nonlocal hwnd
if win32gui.IsWindowVisible(h):
title = win32gui.GetWindowText(h)
if title and target.lower() in title.lower():
hwnd = h
return False
return True
win32gui.EnumWindows(find_window, None)
if not hwnd:
return {"error": f"Window not found: {target}"}
# Get window dimensions
rect = win32gui.GetWindowRect(hwnd)
width = rect[2] - rect[0]
height = rect[3] - rect[1]
if width <= 0 or height <= 0:
return {"error": "Window has invalid dimensions"}
# Capture the window
hwnd_dc = win32gui.GetWindowDC(hwnd)
mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc)
save_dc = mfc_dc.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(mfc_dc, width, height)
save_dc.SelectObject(bitmap)
# Try PrintWindow first (works for most windows)
result = ctypes.windll.user32.PrintWindow(hwnd, save_dc.GetSafeHdc(), 2)
if result == 0:
# Fallback to BitBlt
save_dc.BitBlt((0, 0), (width, height), mfc_dc, (0, 0), win32con.SRCCOPY)
# Convert to PIL Image
bmp_info = bitmap.GetInfo()
bmp_str = bitmap.GetBitmapBits(True)
img = Image.frombuffer(
'RGB',
(bmp_info['bmWidth'], bmp_info['bmHeight']),
bmp_str, 'raw', 'BGRX', 0, 1
)
# Cleanup
win32gui.DeleteObject(bitmap.GetHandle())
save_dc.DeleteDC()
mfc_dc.DeleteDC()
win32gui.ReleaseDC(hwnd, hwnd_dc)
# Save or return base64
if save_path:
img.save(save_path, 'PNG')
return {
"success": True,
"path": save_path,
"width": width,
"height": height,
"window_title": win32gui.GetWindowText(hwnd)
}
else:
buffer = io.BytesIO()
img.save(buffer, format='PNG')
img_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
return {
"success": True,
"width": width,
"height": height,
"window_title": win32gui.GetWindowText(hwnd),
"image_base64": img_base64,
"format": "png"
}
except Exception as e:
return {"error": f"Screenshot failed: {str(e)}"}