form1命名为vcform,对应单元文件为vcap.cpp,头文件为vcap.h。vcform的boarderstyle设置为bsnone,其上放置一个位图按钮bitbtn1,caption为&ok,kind为bkok,onclick事件处理函数中加入一句close()。然后在vcap.h的protected部分加入如前所述消息处理宏和函数onnchittest的声明,以处理标题条的拖动功能。为完成标题的着色和文字输出,双击vcform的onpaint事件以定制formpaint函数,具体代码见下面源码。此外为使窗口有立体感,重载虚函数createparams,以修改窗口的风格。完整的vcap.h和vcap.cpp如下:
//vcap.h #ifndef vcaph #define vcaph #include #include #include #include #include class tvcform : public tform { __published: // ide-managed components tbitbtn *bitbtn1; void __fastcall formpaint(tobject *sender); void __fastcall bitbtn1click(tobject *sender); private: // user declarations protected: void __fastcall onnchittest(tmessage & msg); void __fastcall createparams(tcreateparams& params); begin_message_map message_handler(wm_nchittest,tmessage,onnchittest) end_message_map(tform) public: // user declarations __fastcall tvcform(tcomponent* owner); }; extern package tvcform *vcform; #endif //vcap.cpp #include #pragma hdrstop #include "vcap.h" #pragma package(smart_init) #pragma resource "*.dfm" tvcform *vcform; __fastcall tvcform::tvcform(tcomponent* owner) : tform(owner) { } void __fastcall tvcform::formpaint(tobject *sender) { //绘制宽20的绿色标题条 rect rc; setrect(&rc,0,0,clientwidth,clientheight); canvas->pen->color=clgreen; canvas->brush->color=clgreen; canvas->rectangle(0,0,20,clientheight); //输出旋转文字 char* msg=caption.c_str(); logfont fontrec; memset(&fontrec,0,sizeof(logfont)); fontrec.lfheight = -13; fontrec.lfweight = fw_normal; fontrec.lfescapement = 900; //旋转角度900x0.1度=90度 lstrcpy(fontrec.lffacename,"宋体"); hfont hfont=createfontindirect(&fontrec); hfont hold=::selectobject(canvas->handle,hfont); ::setrect(&rc,0,0,20,clientheight); ::settextcolor(canvas->handle,rgb(255,255,255)); ::textout(canvas->handle,3,clientheight-3,msg,lstrlen(msg)); ::selectobject(canvas->handle,hold); ::deleteobject(hfont); } void __fastcall tvcform::bitbtn1click(tobject *sender) { close(); } void __fastcall tvcform::onnchittest(tmessage & msg) { tpoint pt; pt.x=loword(msg.lparam); pt.y=hiword(msg.lparam); pt =screentoclient(pt); rect rc; setrect(&rc,0,0,20,clientheight); if (ptinrect(&rc,pt)) msg.result = htcaption; else defaulthandler(&msg); } void __fastcall tvcform::createparams(controls::tcreateparams& params) { tform::createparams(params); params.style |= ws_popup; params.style ^= ws_dlgframe; }
vcform的消息处理已经介绍过,这里再对标题条的绘制作简要说明。由于c++builder的tfont没有定义文字旋转旋转的属性,因此用传统的sdk绘图方法。canvas->handle即是代表gdi绘图的hdc。
3 制作对话框控件在开始制作控件之前,先将vcap.cpp中的#pragma package(smart_init)行注释掉。创建控件的步骤是:创建一个单元文件,在其中完成控件的类定义和注册,然后就可以安装了。控件类一般从某个现有类继承导出。制作控件与一般类定义的主要区别在于属性(property)和事件(event),事件也是属性。由属性就带来 |