1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
| import argparse import ctypes import struct import zlib import time import os import sys import tkinter as tk from tkinter import messagebox from pathlib import Path
try: ctypes.windll.shcore.SetProcessDpiAwareness(2) except Exception: try: ctypes.windll.user32.SetProcessDPIAware() except Exception: pass
user32 = ctypes.windll.user32 gdi32 = ctypes.windll.gdi32
SRCCOPY = 0x00CC0020 CAPTUREBLT = 0x40000000
class RECT(ctypes.Structure): _fields_ = [ ("left", ctypes.c_long), ("top", ctypes.c_long), ("right", ctypes.c_long), ("bottom", ctypes.c_long), ]
def get_monitors() -> list[dict]: """연결된 모든 모니터의 정보(해상도 및 가상 화면 좌표)를 가져옵니다.""" monitors = []
@ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(RECT), ctypes.c_void_p) def enum_proc(hmonitor, hdc_monitor, rect_ptr, lparam): r = rect_ptr.contents is_primary = (r.left == 0 and r.top == 0 and (r.right - r.left) > 0) monitors.append({ "hmonitor": hmonitor, "left": r.left, "top": r.top, "right": r.right, "bottom": r.bottom, "width": r.right - r.left, "height": r.bottom - r.top, "is_primary": is_primary }) return True
user32.EnumDisplayMonitors(None, None, enum_proc, 0) return monitors
def capture_screen_raw(left: int, top: int, width: int, height: int) -> bytes: """지정한 좌표와 크기의 화면 영역을 BGRA 바이트 데이터로 캡처합니다.""" if width <= 0 or height <= 0: raise RuntimeError("캡처 크기가 잘못되었습니다.")
hwnd = user32.GetDesktopWindow() hdesktop = user32.GetWindowDC(hwnd) if not hdesktop: raise RuntimeError("데스크톱 디바이스 컨텍스트(DC)를 가져오지 못했습니다.") hmemdc = gdi32.CreateCompatibleDC(hdesktop) if not hmemdc: user32.ReleaseDC(hwnd, hdesktop) raise RuntimeError("호환 메모리 DC를 생성하지 못했습니다.")
bmp = gdi32.CreateCompatibleBitmap(hdesktop, width, height) if not bmp: gdi32.DeleteDC(hmemdc) user32.ReleaseDC(hwnd, hdesktop) raise RuntimeError("호환 비트맵을 생성하지 못했습니다.")
old_obj = gdi32.SelectObject(hmemdc, bmp) try: if gdi32.BitBlt(hmemdc, 0, 0, width, height, hdesktop, left, top, SRCCOPY | CAPTUREBLT) == 0: raise RuntimeError("BitBlt 캡처에 실패했습니다.")
class BITMAPINFOHEADER(ctypes.Structure): _fields_ = [ ("biSize", ctypes.c_uint), ("biWidth", ctypes.c_long), ("biHeight", ctypes.c_long), ("biPlanes", ctypes.c_ushort), ("biBitCount", ctypes.c_ushort), ("biCompression", ctypes.c_uint), ("biSizeImage", ctypes.c_uint), ("biXPelsPerMeter", ctypes.c_long), ("biYPelsPerMeter", ctypes.c_long), ("biClrUsed", ctypes.c_uint), ("biClrImportant", ctypes.c_uint), ]
class BITMAPINFO(ctypes.Structure): _fields_ = [ ("bmiHeader", BITMAPINFOHEADER), ("bmiColors", ctypes.c_uint * 3), ]
bmi = BITMAPINFO() bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER) bmi.bmiHeader.biWidth = width bmi.bmiHeader.biHeight = -height bmi.bmiHeader.biPlanes = 1 bmi.bmiHeader.biBitCount = 32 bmi.bmiHeader.biCompression = 0
buffer_size = width * height * 4 buffer = (ctypes.c_ubyte * buffer_size)() if gdi32.GetDIBits(hmemdc, bmp, 0, height, buffer, ctypes.byref(bmi), 0) == 0: raise RuntimeError("GetDIBits 디바이스 독립 비트맵 복사에 실패했습니다.") return bytes(buffer) finally: gdi32.SelectObject(hmemdc, old_obj) gdi32.DeleteObject(bmp) gdi32.DeleteDC(hmemdc) user32.ReleaseDC(hwnd, hdesktop)
def _write_png_data(bgra: bytes, width: int, height: int, compression_level: int = 6) -> bytes: """BGRA 바이트 데이터를 인메모리 PNG 파일 포맷 바이트로 변환합니다.""" def chunk(tag: bytes, data: bytes) -> bytes: return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
rgba_pixels = bytearray(bgra) rgba_pixels[0::4], rgba_pixels[2::4] = rgba_pixels[2::4], rgba_pixels[0::4] row_len = width * 4 filtered = bytearray() for y in range(height): filtered.append(0) filtered.extend(rgba_pixels[y * row_len : (y + 1) * row_len])
raw = zlib.compress(bytes(filtered), level=compression_level) ihdr = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0) return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", raw) + chunk(b"IEND", b"")
def _write_png(path: Path, bgra: bytes, width: int, height: int) -> None: """BGRA 바이트 데이터를 PNG 파일로 디스크에 저장합니다.""" data = _write_png_data(bgra, width, height, compression_level=6) path.write_bytes(data)
def get_next_index(output_dir: Path, prefix: str) -> int: """중복되지 않는 다음 파일 번호를 가져옵니다.""" if not output_dir.exists(): return 1 import re numbers = [] for f in output_dir.glob("*.png"): if not f.is_file(): continue if f.name.startswith(f"{prefix}_"): match = re.search(r'(\d+)(?:\D*)$', f.stem) if match: numbers.append(int(match.group(1))) if numbers: return max(numbers) + 1 return 1
class ModernButton(tk.Button): """세련된 마우스 호버 효과가 적용된 플랫 스타일 커스텀 버튼입니다.""" def __init__(self, master, bg_color, active_bg, fg_color, *args, **kwargs): super().__init__( master, relief="flat", bd=0, bg=bg_color, fg=fg_color, activebackground=active_bg, activeforeground=fg_color, font=("Segoe UI", 10, "bold"), cursor="hand2", padx=10, pady=8, *args, **kwargs ) self.bg_color = bg_color self.active_bg = active_bg self.bind("<Enter>", lambda e: self.config(bg=active_bg)) self.bind("<Leave>", lambda e: self.config(bg=bg_color))
class CaptureApp: """메인 화면 캡처 GUI 프로그램 애플리케이션입니다.""" def __init__(self, root, output_dir="captures", prefix="capture"): self.root = root self.root.title("화면 캡처") self.root.configure(bg="#1e1e2e") self.root.resizable(False, False) self.root.attributes("-topmost", True) self.output_dir = Path(output_dir) self.prefix = prefix self.monitors = get_monitors() self.main_frame = tk.Frame(root, bg="#1e1e2e", padx=20, pady=20) self.main_frame.pack(fill="both", expand=True) title_label = tk.Label( self.main_frame, text="MONITOR CAPTURE", font=("Segoe UI", 14, "bold"), bg="#1e1e2e", fg="#89b4fa" ) title_label.pack(pady=(0, 15)) tk.Label( self.main_frame, text="캡처할 모니터 선택:", font=("Segoe UI", 9, "bold"), bg="#1e1e2e", fg="#a6adc8" ) monitor_options = [] default_idx = 0 for idx, m in enumerate(self.monitors): primary_text = " (주 모니터)" if m["is_primary"] else "" monitor_options.append(f"모니터 {idx + 1}: {m['width']}x{m['height']}{primary_text}") if m["is_primary"]: default_idx = idx if not monitor_options: monitor_options = ["모니터 정보를 찾을 수 없습니다."] self.selected_monitor_str = tk.StringVar(value=monitor_options[default_idx]) self.monitor_menu = tk.OptionMenu(self.main_frame, self.selected_monitor_str, *monitor_options) self.monitor_menu.config( bg="#313244", fg="#cdd6f4", activebackground="#45475a", activeforeground="#cdd6f4", relief="flat", highlightthickness=0, font=("Segoe UI", 10), cursor="hand2", padx=10, pady=5 ) self.monitor_menu["menu"].config( bg="#313244", fg="#cdd6f4", activebackground="#45475a", activeforeground="#cdd6f4", font=("Segoe UI", 10), relief="flat" ) self.monitor_menu.pack(fill="x", pady=(0, 15)) self.status_card = tk.Frame( self.main_frame, bg="#252538", padx=15, pady=15, highlightbackground="#313244", highlightthickness=1 ) self.status_card.pack(fill="x", pady=(0, 20)) self.status_title = tk.Label( self.status_card, text="상태", font=("Segoe UI", 9, "bold"), bg="#252538", fg="#a6adc8" ) self.status_title.pack(anchor="w") self.status_var = tk.StringVar(value="대기 중 (모니터 선택 후 캡처 버튼 클릭)") self.status_label = tk.Label( self.status_card, textvariable=self.status_var, font=("Segoe UI", 10), bg="#252538", fg="#cdd6f4", wraplength=260, justify="left" ) self.status_label.pack(anchor="w", pady=(5, 0)) self.capture_btn = ModernButton( self.main_frame, bg_color="#a6e3a1", active_bg="#94e2d5", fg_color="#11111b", text="선택한 모니터 캡처", command=self.start_capture ) self.capture_btn.pack(fill="x", pady=(0, 10)) self.btn_frame = tk.Frame(self.main_frame, bg="#1e1e2e") self.btn_frame.pack(fill="x") self.folder_btn = ModernButton( self.btn_frame, bg_color="#313244", active_bg="#45475a", fg_color="#cdd6f4", text="캡처 폴더 열기", command=self.open_folder ) self.folder_btn.pack(side="left", fill="x", expand=True) def open_folder(self): """저장용 캡처 폴더를 파일 탐색기에서 엽니다.""" self.output_dir.mkdir(parents=True, exist_ok=True) try: os.startfile(self.output_dir) except Exception as e: messagebox.showerror("오류", f"폴더를 열지 못했습니다: {e}") def start_capture(self): """캡처를 시작하기 위해 메인 GUI 창을 일시적으로 숨깁니다.""" self.root.withdraw() self.root.after(200, self.do_capture) def do_capture(self): """선택한 모니터를 캡처한 뒤 저장하고 GUI 창을 복원합니다.""" try: sel_str = self.selected_monitor_str.get() if sel_str.startswith("모니터 "): m_idx = int(sel_str.split(":")[0].split(" ")[1]) - 1 else: m_idx = 0 if m_idx >= len(self.monitors): raise ValueError("선택한 모니터를 찾을 수 없습니다.") monitor = self.monitors[m_idx] left = monitor["left"] top = monitor["top"] width = monitor["width"] height = monitor["height"] bgra_data = capture_screen_raw(left, top, width, height) self.output_dir.mkdir(parents=True, exist_ok=True) file_idx = get_next_index(self.output_dir, self.prefix) filename = f"{self.prefix}_{file_idx:04d}.png" filepath = self.output_dir / filename _write_png(filepath, bgra_data, width, height) self.status_var.set(f"캡처 완료 및 저장:\n{filename}") self.status_label.config(fg="#a6e3a1") except Exception as e: messagebox.showerror("오류", f"캡처 작업 중 오류가 발생했습니다:\n{e}") self.status_var.set("캡처 실패") self.status_label.config(fg="#f38ba8") finally: self.root.deiconify() self.root.attributes("-topmost", True)
def main() -> int: parser = argparse.ArgumentParser(description="모니터 화면 자동 캡처 프로그램") parser.add_argument("--out", default="captures", help="저장할 디렉토리 경로 (기본값: captures)") parser.add_argument("--prefix", default="capture", help="파일명 접두사 (기본값: capture)") args = parser.parse_args() root = tk.Tk() app = CaptureApp(root, output_dir=args.out, prefix=args.prefix) root.mainloop() return 0
if __name__ == "__main__": sys.exit(main())
|