RichEdit那点儿事(一)

一、加载riched20.dll

如果对话框里含用RichEdit控件,在创建这个对话框之前(或在需要动态创建RichEdit之前),必须首先加载相应的动态链接库,否则创建会失败。不同的库支持不同的RichEdit版本,对应关系如下:

控件版本 动态链接库名
1.0
Riched32.dll
2.0
Riched20.dll
3.0
Riched20.dll
4.1
Msftedit.dll

不同的Windows版本自带的RichEdit库不同,对应关系如下:

Windows XP SP1 Includes Rich Edit 4.1, Rich Edit 3.0, and a Rich Edit 1.0 emulator.
Windows XP Includes Rich Edit 3.0 with a Rich Edit 1.0 emulator.
Windows Me Includes Rich Edit 1.0 and 3.0.
Windows 2000 Includes Rich Edit 3.0 with a Rich Edit 1.0 emulator.
Windows NT 4.0 Includes Rich Edit 1.0 and 2.0.
Windows 98 Includes Rich Edit 1.0 and 2.0.
Windows 95 Includes only Rich Edit 1.0. However, Riched20.dll is compatible with Windows 95 and may be installed by an application that requires it.

示例:

class RichEditLib {
HMODULE h_;
public:
RichEditLib()
: h_(LoadLibrary(_T("riched20.dll")))
{
if (!h_)
throw std::runtime_error();
}
~RichEditLib() {
FreeLibrary(h_);
}
};
int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int) {
try {
....
RichEditLib rel;
} catch (std::exception & ex) {
::MessageBoxA(::GetActiveWindow(), ex.what(), NULL, MB_OK | MB_ICONSTOP);
return -1;
}
....
return 0;
}

二、常用方法

1、得到控件中包含文本的行数

向控件发送消息EM_GETLINECOUNT可得到它包含的文本的总行数,但要注意当文本为空的时候,它还是返回1,换句话说,它返回的总行数永远不会小于1。所以要真正知道现在有多少行,必须做些小处理:

int getRichEditLineCount(HWND richedit) {
int result = SendMessage(richedit, EM_GETLINECOUNT, 0, 0);
const int firstCharPosOfLastLine = (int)SendMessage(richedit, EM_LINEINDEX, result-1, 0);
if (!SendMessage(richedit, EM_LINELENGTH, firstCharPosOfLastLine, 0))
--result;
return result;
}

2、取最末尾字符的位置

int getRichEditTail(HWND richedit) {
int const lines = getRichEditLineCount(richedit);
int result = (int)SendMessage(richedit, EM_LINEINDEX, lines-1, 0);
result += (int)SendMessage(richedit, EM_LINELENGTH, result, 0);
return result;
}

3、滚动到最后一行

如果写代码在RichEdit里添加一行一行的文本,有时候需要让它自动滚动到最后一行(比如日志、聊天室等),向它发送WM_VSCROLL消息即可:

SendMessage(richedit, WM_VSCROLL, SB_BOTTOM, 0)

你可能感兴趣的:(Windows编程,windows,winapi,exception,application,xp,聊天)