平台为win32+duilib,其他环境类似。
static DWORD CALLBACK streamInCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
ReadFile((HANDLE)dwCookie, pbBuff, cb, (LPDWORD)pcb, NULL);//读取数据
return 0;
}
BOOL ReadFileByStreamIn(CRichEditUI* hRichEdit, LPCTSTR pszFileName)
{
HRESULT hr;
HANDLE hFile = CreateFile(pszFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return FALSE;
EDITSTREAM es;
es.dwCookie = (DWORD_PTR)hFile;
es.pfnCallback = streamInCallback;
hRichEdit->SetSel(0, -1);
DWORD dwStart, dwEnd;
hRichEdit->GetSel((long&)dwStart, (long&)dwEnd);
hRichEdit->SetSel(dwEnd + 1, dwEnd + 1);
//hRichEdit->ReplaceSel(L"
", TRUE);
CDuiString strFileName(pszFileName);
CDuiString strExt = strFileName.Right(4);
if (strExt == _T(".txt"))
hr = hRichEdit->StreamIn(SF_TEXT | SFF_SELECTION, es);
else if (strExt == _T(".rtf"))
hr = hRichEdit->StreamIn(SF_RTF | SFF_SELECTION, es);
CloseHandle(hFile);
if (FAILED(hr))
{
return FALSE;
}
return TRUE;
}
写入文本可以此类推。