// 将代码变为面向对象化,创建一个名为TextEditor的类来管理编辑文本的操作 #include #include #include #include <windows.h>

class TextEditor { private: HWND hWnd; // 文本编辑窗口句柄 FILE *fp; // 文件指针 char text[10240]; // 存储文本内容的缓冲区 char buffer[20240]; // 存储文本行和文本内容的缓冲区

public: void sleep(int milliseconds) { Sleep(milliseconds); }

void getCursorPosition(POINT& pt) {
    GetCursorPos(&pt);
}

HWND getWindowFromPoint(const POINT& pt) {
    return WindowFromPoint(pt);
}

void screenToClient(HWND hWnd, POINT& pt) {
    ScreenToClient(hWnd, &pt);
}

HWND getChildWindowFromPoint(HWND hParent, const POINT& pt) {
    return ChildWindowFromPoint(hParent, pt);
}

void getWindowText(HWND hWnd, char* text) {
    SendMessage(hWnd, WM_GETTEXT, 10240, (LPARAM)text);
}

void setWindowText(HWND hWnd, const char* text) {
    SendMessage(hWnd, WM_SETTEXT, NULL, (LPARAM)text);
}

bool isKeyPressed(int virtualKey) {
    return GetAsyncKeyState(virtualKey) && 0x8000;
}

void openFile(const char* fileName) {
    fp = fopen(fileName, 'r');
    if (NULL == fp) {
        printf('open failed.\n');
        exit(-1);
    }
}

void closeFile() {
    fclose(fp);
}

void processFile() {
    int line_num = 0; // 文件行数
    int line_len = 0; // 文件每行的长度
    char buf[20240] = {0}; // 行数据缓存

    while(fgets(buf, 20240, fp)) {
        line_num++;
        line_len = strlen(buf);
        // 排除换行符
        if ('\n' == buf[line_len - 1]) {
            buf[line_len - 1] = '\0';
            line_len--;
            if (0 == line_len) {
                //空行 
                continue;
            }
        }
        // windows文本排除回车符
        if ('\r' == buf[line_len - 1]) {
            buf[line_len - 1] = '\0';
            line_len--;
            if (0 == line_len) {
                //空行 
                continue;
            }
        }
        // showtext 
        sprintf(buffer, '%s\r\n%s', buf, text);
        setWindowText(hWnd, buffer);
        // waitF7Down 
        while(!isKeyPressed(VK_F7)) {
            if (isKeyPressed(VK_F6)) {
                // TODO实现返回上一行 
                fseek(fp, -2 * (line_len + 2), SEEK_CUR); // 返回上一行的位置 
                break;
            }
        }
        while(isKeyPressed(VK_F7));
    }

    if (0 == feof) {
        // 未读到文件末尾
        printf('fgets error\n');
        exit(-1);
    }
}

};

int main() { TextEditor editor; editor.sleep(2000);

POINT pt, ptScreen;
editor.getCursorPosition(ptScreen);
HWND hParent = editor.getWindowFromPoint(ptScreen);
editor.screenToClient(hParent, pt);
editor.getChildWindowFromPoint(hParent, pt);

char text[10240], buffer[20240];
editor.getWindowText(hWnd, text);

editor.openFile('text.txt');
editor.processFile();
editor.closeFile();

return 0;
C++ 面向对象代码重构:使用 TextEditor 类实现文本编辑器

原文地址: https://www.cveoy.top/t/topic/qklT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录