2

我在我的简单应用程序中有一个RichEdit控件,我希望用它来模拟类似控制台的显示。我希望能够拥有x行数的缓冲区(例如 300 行),并且每当添加一行时,如果新行超过阈值,我还想删除最旧的(顶部)行x。我还希望它在添加时自动滚动到底部以显示最新的行。

我一直在使用SetWindowText并取得了一些成功,但是在我看来,可能有一种更有效的方法可以将文本附加到末尾并从开头删除文本,而不必每次都替换所有文本。这是真的吗,如果是这样,我该怎么做?

另外,添加新文本时如何使其自动滚动到窗口底部?

这是使用 C 中的 Win32 API,我没有使用 MFC 版本RichEdit(仅在 XP 和 Vista 上使用 vanilla Win32 API)。

4

2 回答 2

3

要添加文本,请将所选内容设置为文本的末尾 (EM_SETSEL),然后将所选内容替换为新文本 (EM_REPLACESEL)。

要滚动到底部,您可以向其发送带有 SB_BOTTOM 的 WM_VSCROLL。

于 2010-02-05T23:55:06.467 回答
1

我发给你一些示例类的方法cConsole

class cConsole {
private:
    //-------------------
    int lines;
    int max_lines;             // Init it with your choise ( 300 )
    //-------------------
    char* buf;
    int buf_size;
    //-------------------
    int CheckMemory( int size );
    void NewLine( int new_lines );
    void InternalPrint( char* msg, int size );

public:
    HWND hWin;
    void Print( char* msg );    // Add text data through this methods
    void Print( char* msg, int size );
    cConsole( );
    ~cConsole( );
};

int cConsole::CheckMemory( int size ) {
int rv = 1;
if( size + 16 >= buf_size ) {
    int new_buf_size = size + 1024;
    char* new_buf = ( char* )realloc( buf, new_buf_size );
    if( new_buf != NULL ) {
        buf = new_buf;
        buf_size = new_buf_size;
    } else {
        rv = 0;
    }
}
return rv;
}

void cConsole::NewLine( int new_lines ) {
int rem_lines = ( new_lines + lines + 1 ) - max_lines;
if( rem_lines <= 0 ) {
    lines += new_lines;
} else {
    int sel = SendMessage( hWin, EM_LINEINDEX, rem_lines, 0 );

    SendMessage( hWin, EM_SETSEL, 0, (LPARAM)sel );
    SendMessage( hWin, EM_REPLACESEL, FALSE, (LPARAM)"" );
    SendMessage( hWin, WM_VSCROLL, SB_BOTTOM, NULL );

    lines = max_lines - 1;
}
}

void cConsole::Print( char* msg ) { InternalPrint( msg, -1 ); }
void cConsole::Print( char* msg, int size ) { if( size < 0 ) size = 0; InternalPrint( msg, size ); }

void cConsole::InternalPrint( char* msg, int size ) {
int s, t = 0;
int new_lines = 0;
char* tb;

// msg only mode
if( size == -1 ) size = 0x7fffffff;

if( msg != NULL && size && CheckMemory( t ) ) {
    for( s = 0; msg[ s ] && ( s < size ); s++ ) {
        if( msg[ s ] == '\r' ) continue;
        if( !CheckMemory( t ) ) break;
        if( msg[ s ] == '\n' ) {
            ++new_lines;
            buf[ t++ ] = '\r';
        }
        buf[ t++ ] = msg[ s ];
    }
    buf[ t ] = '\0';
}
if( t && msg != NULL ) {
    tb = buf;
} else {
    ++new_lines;
    tb = "\r\n";
}

SendMessage( hWin, EM_SETSEL, (WPARAM)-2, (LPARAM)-1 );
SendMessage( hWin, EM_REPLACESEL, FALSE, (LPARAM)tb );
SendMessage( hWin, WM_VSCROLL, SB_BOTTOM, NULL );

if( new_lines ) NewLine( new_lines );
}

建立自己的班级并检查一下!

于 2012-11-26T16:03:13.480 回答