메뉴 여닫기
개인 메뉴 토글
로그인하지 않음
만약 지금 편집한다면 당신의 IP 주소가 공개될 수 있습니다.

커서 Caret 텍스트 찾기 프로그램

데브카페

Windows 에서 커서(Caret)가 위치 텍스트 출력 프로그램

  • Windows 에서 캐럿(커서) 위치의 텍스트를 출력하는 C++과 AutoIt ,Python 소스 예제입니다.

C++ 버전

#include <windows.h>
#include <iostream>
#include <string>

std::string GetTextAroundCaret(HWND hWnd) {
    DWORD startPos, endPos;
    CHAR buffer[1024] = {0};
    
    // 현재 포커스가 있는 윈도우 핸들 가져오기
    if (hWnd == NULL) {
        hWnd = GetFocus();
    }
    
    // Edit 컨트롤인지 확인
    char className[256];
    GetClassNameA(hWnd, className, sizeof(className));
    
    if (strcmp(className, "Edit") != 0) {
        return "Not an Edit control";
    }
    
    // 현재 선택 영역 가져오기
    SendMessageA(hWnd, EM_GETSEL, (WPARAM)&startPos, (LPARAM)&endPos);
    
    // 텍스트 길이 가져오기
    int textLength = GetWindowTextLengthA(hWnd);
    
    // 전체 텍스트 가져오기
    GetWindowTextA(hWnd, buffer, textLength + 1);
    
    // 캐럿 주변 텍스트 추출 (예: 캐럿 앞 10자, 뒤 10자)
    int start = max(0, (int)startPos - 10);
    int end = min(textLength, (int)startPos + 10);
    
    return std::string(buffer + start, buffer + end);
}

int main() {
    std::cout << "Caret 위치 텍스트를 가져오는 프로그램 (10초간 실행)" << std::endl;
    
    for (int i = 0; i < 10; i++) {
        HWND foregroundWindow = GetForegroundWindow();
        HWND focusWindow = GetFocus();
        
        std::string text = GetTextAroundCaret(focusWindow);
        std::cout << "Caret 주변 텍스트: " << text << std::endl;
        
        Sleep(1000); // 1초 대기
    }
    
    return 0;
}

AutoIt 버전


#include <WinAPI.au3>
#include <EditConstants.au3>
#include <Math.au3>

Func GetCaretText()
    Local $hWnd = _WinAPI_GetFocus()
    If $hWnd = 0 Then Return "포커스된 창이 없습니다."
    
    ; 클래스 이름 확인
    Local $sClass = _WinAPI_GetClassName($hWnd)
    If $sClass <> "Edit" Then Return "Edit 컨트롤이 아닙니다: " & $sClass
    
    ; 현재 선택 위치 가져오기
    Local $iStart = _SendMessage($hWnd, $EM_GETSEL)
    Local $iEnd = BitShift($iStart, 16)
    $iStart = BitAND($iStart, 0xFFFF)
    
    ; 전체 텍스트 가져오기
    Local $sText = ControlGetText("[ACTIVE]", "", $hWnd)
    If @error Then Return "텍스트를 가져올 수 없습니다."
    
    ; 캐럿 주변 텍스트 추출 (앞 10자, 뒤 10자)
    Local $iTextLen = StringLen($sText)
    Local $iFrom = _Max(0, $iStart - 10)
    Local $iTo = _Min($iTextLen, $iStart + 10)
    
    Return StringMid($sText, $iFrom + 1, $iTo - $iFrom)
EndFunc

; 메인 프로그램
ToolTip("캐럿 위치 텍스트를 가져오는 AutoIt 프로그램 (10초간 실행)", 0, 0)

For $i = 1 To 10
    Local $sText = GetCaretText()
    ConsoleWrite("캐럿 주변 텍스트: " & $sText & @CRLF)
    Sleep(1000)
Next

Exit

프로그램 사용 방법

    • C++ 버전:
      - Visual Studio 등으로 컴파일 후 실행
      - 10초 동안 1초 간격으로 포커스된 Edit 컨트롤의 캐럿 위치 주변 텍스트 출력
    • AutoIt 버전:
      - AutoIt 스크립트로 저장 후 실행

++: - 10초 동안 1초 간격으로 콘솔에 캐럿 위치 주변 텍스트 출력

주의 사항

- 이 프로그램은 표준 Edit 컨트롤에서만 작동합니다.
- RichEdit, Chrome, 워드프로세서 등 다른 컨트롤에서는 작동하지 않을 수 있습니다.
- 관리자 권한이 필요한 경우도 있을 수 있습니다.

Python 버전

  • pywin32 라이브러리 (pip install pywin32) 설치
import win32gui
import win32con
import win32api
import win32ui
import time

def get_caret_text():
    try:
        # 현재 포커스된 창의 핸들을 가져옴
        hwnd = win32gui.GetForegroundWindow()
        if not hwnd:
            return "포커스된 창을 찾을 수 없습니다."

        # 창의 클래스 이름 가져오기
        class_name = win32gui.GetClassName(hwnd)

        # 편집 컨트롤(Edit control)인지 확인
        if "Edit" in class_name or "RichEdit" in class_name:
            # 텍스트 길이 가져오기
            text_length = win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
            if text_length > 0:
                # 텍스트 버퍼 생성 및 텍스트 가져오기
                buffer = win32gui.PyMakeBuffer(text_length + 1)
                win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, text_length + 1, buffer)
                text = buffer[:text_length].decode('utf-8')

                # 캐럿 위치 가져오기
                sel_start, sel_end = win32gui.SendMessage(hwnd, win32con.EM_GETSEL, 0, 0)
                sel_start = win32api.LOWORD(sel_start)
                sel_end = win32api.LOWORD(sel_end)

                # 캐럿 근처 텍스트 추출 (예: 캐럿 앞뒤 10자)
                start = max(0, sel_start - 10)
                end = min(text_length, sel_end + 10)
                caret_text = text[start:end]
                return f"캐럿 위치 텍스트: {caret_text}\n전체 텍스트: {text}\n캐럿 위치: {sel_start}"
            else:
                return "텍스트가 없습니다."
        else:
            return "현재 포커스된 창은 텍스트 편집 컨트롤이 아닙니다."
    except Exception as e:
        return f"오류 발생: {str(e)}"

# 프로그램 실행
if __name__ == "__main__":
    print("5초 후에 현재 캐럿 위치의 텍스트를 조회합니다...")
    time.sleep(5)  # 사용자가 텍스트 편집 창에 포커스를 맞출 시간을 줌
    result = get_caret_text()
    print(result)

코드 설명

  • 필요한 모듈: pywin32를 사용하여 Windows API를 호출합니다.
  • 포커스된 창 확인: GetForegroundWindow로 현재 포커스된 창의 핸들을 가져옵니다.
  • 텍스트 컨트롤 확인: 창의 클래스 이름이 Edit 또는 RichEdit인지 확인하여 텍스트 입력 창인지 판단합니다.
  • 텍스트 가져오기: WM_GETTEXT 메시지로 창의 전체 텍스트를 가져오고, EM_GETSEL 메시지로 캐럿의 시작/끝 위치를 가져옵니다.
  • 캐럿 주변 텍스트 추출: 캐럿 위치를 기준으로 앞뒤 10자 내의 텍스트를 추출합니다.
  • 실행: 프로그램 실행 후 5초 대기하여 사용자가 원하는 텍스트 창(예: 메모장)에 포커스를 맞출 시간을 줍니다.

사용 방법

  • Python 환경에 pywin32를 설치합니다:
pip install pywin32
    위 코드를 .py 파일로 저장합니다(예:caret_text.py).
  • 메모장이나 다른 텍스트 편집기(예: Notepad++, Word 등)를 열고 텍스트를 입력한 뒤 커서를 원하는 위치에 놓습니다.
  • 코드를 실행하면 5초 후 현재 캐럿 위치 주변의 텍스트와 전체 텍스트를 출력합니다.

주의사항

  • 이 코드는 Windows의 기본 텍스트 편집 컨트롤(Edit, RichEdit)에서 작동합니다. 일부 응용프로그램(예: 웹 브라우저의 텍스트 입력란)은 다른 방식으로 구현될 수 있어 작동하지 않을 수 있습니다.
  • 웹 브라우저나 특수 응용프로그램의 경우, 추가로 UIAutomation이나 pyautogui 같은 라이브러리가 필요할 수 있습니다.
  • 코드 실행 전, 포커스된 창이 텍스트 입력 창인지 확인하세요(예: 메모장).

pywinauto 이용

만약 더 복잡한 응용프로그램(예: 브라우저)에서 캐럿 위치의 텍스트를 가져오고 싶다면, Microsoft의 UI Automation 프레임워크를 사용할 수 있습니다. 아래는 pywinauto를 사용한 간단한 예제입니다:

from pywinauto import Application
import time

def get_caret_text_uia():
    try:
        app = Application().connect(focused=True)
        focused_window = app.window(focused=True)
        # 텍스트 컨트롤 찾기
        text_control = focused_window.child_window(control_type="Edit")
        if text_control.exists():
            text = text_control.window_text()
            caret_pos = text_control.get_selection()[0]
            caret_text = text[max(0, caret_pos-10):caret_pos+10]
            return f"캐럿 위치 텍스트: {caret_text}\n전체 텍스트: {text}\n캐럿 위치: {caret_pos}"
        else:
            return "텍스트 컨트롤을 찾을 수 없습니다."
    except Exception as e:
        return f"오류 발생: {str(e)}"

if __name__ == "__main__":
    print("5초 후에 현재 캐럿 위치의 텍스트를 조회합니다...")
    time.sleep(5)
    result = get_caret_text_uia()
    print(result)
  • 추가 설치
pip install pywinauto

참고

    • pywin32 방식은 가볍고 빠르지만 기본 Windows 컨트롤에 한정됩니다.
    • pywinauto는 더 복잡한 응용프로그램에서 작동할 가능성이 높지만 설정이 더 복잡할 수 있습니다.

Comments