這是一個注冊EXE,OBJ,BIN三種類型文件,當其被RichEdit打開時會自動轉換為16進制顯示的例子
--------------------------------------------------------------------------------
步驟:
第一:要從TCoriversion派生出一個新類
第二:重載CorrvertReadStream函數
第三:在主窗體的OnCreate函數中登記文件類型。用RichEdit的.RegisterConversionFormat函數
//---------------------------------------------------------------------------
// 從TCoriversion派生出一個新類
class THexConversion : public TConversion
{
public:
virtual int __fastcall ConvertReadStream(TStream *pStream,
char *pSrcBuffer, int nBufSize);
};
//---------------------------------------------------------------------------
// 重載 ConvertReadStream 函數
int __fastcall THexConversion::ConvertReadStream(TStream *pStream,
char *pSrcBuffer, int nBufSize)
{
String strTemp;
unsigned char szDstBuffer[16];
int n;
int nResult;
if(nBufSize <= 82)
return 0;
// 行號,類似UtrlEdit,用8位來表示
strTemp = strTemp.sprintf("%.8xh: ", pStream->Position);
n = pStream->Read(szDstBuffer, 16);
if(n == 0)
return 0;
// 顯示字符的ASCII值,四個一組,中間用空格分隔
for(int i=0; i<n; i++)
{
AppendStr(strTemp, IntToHex(szDstBuffer[i], 2) + ' ');
if((i+1) % 4 == 0)
AppendStr(strTemp, ' ');
}
String str;
str.StringOfChar(' ', 65 - strTemp.Length());
AppendStr(strTemp, str + "; ");
// 顯示實際的Ascii字符,如果是非可打印字符,用'.'代替
for(int i=0; i<n; i++)
{
if((szDstBuffer[i] < 32) || (szDstBuffer[i] > 126))
szDstBuffer[i] = '.';
AppendStr(strTemp, (char)szDstBuffer[i]);
}
AppendStr(strTemp, "\n");
StrCopy(pSrcBuffer, strTemp.c_str());
nResult = strTemp.Length();
// 顯示加載進度
Form1->Process(pStream->Position);
Application->ProcessMessages();
return nResult;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
// 登記文件類型
RichEdit1->RegisterConversionFormat(NULL, "bin", __classid(THexConversion));
RichEdit1->RegisterConversionFormat(NULL, "obj", __classid(THexConversion));
RichEdit1->RegisterConversionFormat(NULL, "exe", __classid(THexConversion));
}
//---------------------------------------------------------------------------
// 自定義函數,須在.h文件中TForm1類中聲明一下,例如:
// public:
// void __fastcall Process(int nPos);
//
// 為防止不負責任的轉載者,在些注明原作及修改者信息,請見諒。
// 原作:張晶晶
// 修改:ccrun(老妖),歡迎光臨C++Builder研究: http://www.ccrun.com
//---------------------------------------------------------------------------
void __fastcall TForm1::Process(int nPos)
{
// 顯示加載進度
StatusBar1->SimpleText = "正在處理... " + String(nPos);
StatusBar1->Update();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
RichEdit1->Lines->LoadFromFile("C:\\123\\123.exe");
StatusBar1->SimpleText = "加載完成!";
}
//---------------------------------------------------------------------------