RICHEDIT 富文本控件可以容纳各种字体,那么如果我们想要知道文本的总行高如何做呢?
比如,我们想判断,richedit中的文本内容有没有超出richedit 的范围,如何实现呢?
1,需要使用EM_FORMATRANGE 消息 http://msdn.microsoft.com/en-us/library/bb788020%28VS.85%29.aspx
2,实现的代码如下:(下面是BCB 的实现,stackoverflow上有delphi的实现
http://stackoverflow.com/questions/3244139/how-to-get-text-extent-of-richedit-in-delphi)
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { RichEdit1->Text = RichEdit1->Text.TrimRight(); int LogX,LogY; HDC richdc = GetDC(RichEdit1->Handle); LogX = GetDeviceCaps(richdc, LOGPIXELSX); LogY = GetDeviceCaps(richdc, LOGPIXELSY); FORMATRANGE formatrange = {0}; formatrange.hdc = richdc; formatrange.hdcTarget = richdc; formatrange.rc.left = 0; formatrange.rc.top = 0; formatrange.rc.right = RichEdit1->ClientWidth * 1440 / LogX; formatrange.rc.bottom= Screen->Height* 1440 / LogY; formatrange.rcPage = formatrange.rc; formatrange.chrg.cpMin = 0; formatrange.chrg.cpMax = -1; RichEdit1->Perform(EM_FORMATRANGE,0,(long)&formatrange); int totalHeight = formatrange.rc.bottom * LogY / 1440; ShowMessage("文本总高度"+IntToStr(formatrange.rc.bottom * LogY / 1440)); RichEdit1->Perform(EM_FORMATRANGE,0,NULL);//free the cache if (totalHeight > (RichEdit1->ClientHeight+3)) { ShowMessage("文字超出范围!"); }
ReleaseDC(RichEdit1->Handle,richdc); } //--------------------------------------------------------------------------- void __fastcall TForm1::Button2Click(TObject *Sender) { RichEdit1->Font->Size++; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button3Click(TObject *Sender) { RichEdit1->Font->Size--; } //---------------------------------------------------------------------------