您的位置:首页 > 编程语言 > C语言/C++

Creating and Using custom controlsin VC++

2012-04-22 08:52 417 查看

CreatingandUsingcustomcontrolsinVC++

Introduction

Hithere!ThisismyfourtharticleforTheCodeProject.MigratingtowardstheVC++,IhavefirstlyconcernedwiththecustomcontrolsthatcanbecreatedwiththehelpofVC++,sincethatisavery
helpfulfeaturewhenyouwanttomodifythecontentsofanycontroloryouwanttocreateyourown.So,Ihavedecidedtowritethisarticlesothenewdevelopersorthebeginnerswhowanttodevelopanycontrolswillgetsomehelpfrommysmallknowledge.
Now,that’sallfortheintroductionnow,Iammovingtowardstheoriginalpointofview:thatis,howandwhytocreateanycustomcontrol.AsIhaveinterestindevelopingapplicationsinWin32APIbecauseofits
smallsizeandstandaloneexecutables,InevereverhadworkedontheVC++but,itistoomuchpowerfullanguageandthepower-featuresinithaveattractedmetowardsit.Oneofthemisthecustomcontrol.ToomuchofarticlesontheCodeProject
haveusedthecustomcontrols.ButwhenIhavereadthemfirstly,Ihaven’tunderstoodhowtocreateandgetthemessagesandthenprocessonthatmessagesinthesimpleWindowsapplications.Thecustomcontrolsgivethedeveloperaconvenientwaytocreatethe
controlandvisualizethatastheregularcontrol.
(AsIamabeginnerwithVC++,pleasetellmeifthereareanymistakesinthisarticle).

Whereisit?

Now,thequestionisthat,whereisthecustomcontrol?So,answerisbelow.Thepicturebelowshowsthecustomcontrol,itliesinthecontrolbar.

Thepictureshowsthepositionofthecustomcontrol.Youareabletoselectitanddrawdirectlyonyourformresource.
Themainproblemarisesafteryouhaveputthatcontrolonyourformthatifyoubuildandexecutetheprogramtheviewisnotavailablesinceyouhaven'tselectedanyclassforyourcontrol,sothatpartisdiscussedinalatersection.

CreatingaClass

Now,thefigureaboveshowsthecustomcontrolasdrawnontheformview.Now,youhavetorightclickonthatandselectClassWizardformthepopupmenu.

Selectingaclass

AfteryouhaveclickedtheClasswizard,thedialogshownhereappearsonthescreen.Fromit,selectAddClassandthenNew.

Now,onceyouhaveclickedtheNewbutton,thedialogtoselectthebaseclassforourcustomcontrolwillappearasbelow.Here,youhavemultiplechoicestoselectanybaseclass.Thatmeansyoucancustomizethebasiccontrol
like,staticcontrolortheeditcontrol,byaddingthenewfeatures,oryouareabletocreateafullynewcontrol.Ihavedecidedtocreateafullynewcontrollikeapad,andso,Ihaveselectedabasic
CWnd
class
asabaseclass.

Andfinally,youhavecreatedaclassforyourcontrol.Now,theseriouspartbegins....
Astheclasshasbeencreatedbyusingthe
CWnd
asabase,wewillhavetoregisterthisclasssincethisisacustomclass.So,wewillhavetowritethefunction
RegisterWndClass()
to
dothat.Itmaybecodedasbelow...
Collapse|CopyCode

BOOLMyCustomControl::RegisterWndClass()

{

WNDCLASSwindowclass;

HINSTANCEhInst=AfxGetInstanceHandle();


//Checkweathertheclassisregisterdalready

if(!(::GetClassInfo(hInst,MYWNDCLASS,&windowclass)))

{

//Ifnotthenwehavetoregisterthenewclass

windowclass.style=CS_DBLCLKS;//|CS_HREDRAW|CS_VREDRAW;

windowclass.lpfnWndProc=::DefWindowProc;

windowclass.cbClsExtra=windowclass.cbWndExtra=0;

windowclass.hInstance=hInst;

windowclass.hIcon=NULL;

windowclass.hCursor=AfxGetApp()->LoadStandardCursor(IDC_ARROW);

windowclass.hbrBackground=::GetSysColorBrush(COLOR_WINDOW);

windowclass.lpszMenuName=NULL;

windowclass.lpszClassName=MYWNDCLASS;


if(!AfxRegisterClass(&windowclass))

{

AfxThrowResourceException();

returnFALSE;

}

}


returnTRUE;

}


Inthisway,wehaveregisteredthenewwindowclass.Now,youwillhavetoaddthatfunctioninyourdefaultclassconstructorasfollows:
Collapse|CopyCode

MyCustomControl::MyCustomControl()

{

//RegisterMywindowclass

RegisterWndClass();

}


Ithinkanyonewillthinkwhatis
MYWNDCLASS
.Theansweristhatitisthedefinedclassnameforourcustomclass.ItisdefinedatthetopoftheMyCustomControl.hfileas
follows:
Collapse|CopyCode

#defineMYWNDCLASS"MyDrawPad"


Now,wehaveourownclasscalled
MyDrawPad
.

AttachingClasstotheCustomControl:

Withallthingsgoingright,weareapproachingtowardscompletingthecreationofthecustomcontrol.Thelastthingremainingistosetthecustomcontrolasourcreatedwindowclass.Forthat,rightclickonthecustomcontrolin
theresourceviewandthenselectthepropertiesofthecustomcontrol.Thedialogboxwillappearasshownbelow...

Then,settheclassnameas
MyDrawPad
thatwehavecreatedearlier.Hereyoucanselectthewindowstylebychangingthehexadecimalvalueinthestyleeditbox.
Ihaveexperimentedwithsomeofthevalues,youcanalsotrythem.

DoingtheDataExchange

Now,allthethingsaresetup.Butthedatamustbeexchangedbetweenthewindowandourapplication.So,addavariableforourcustomcontroltoyourdialogclassasfollows:
Collapse|CopyCode

//Implementation

protected:

HICONm_hIcon;

MyCustomControlm_drawpad;//Thisisourcustomcontrol


Afterthat,youhavetoaddthefollowingcodeinthe
DoDataExchage()
functiontointeractwiththecustomcontrol.
Collapse|CopyCode

voidCCustomControlDlg::DoDataExchange(CDataExchange*pDX)

{

CDialog::DoDataExchange(pDX);

//{{AFX_DATA_MAP(CCustomControlDlg)

//NOTE:theClassWizardwilladdDDXandDDVcallshere

DDX_Control(pDX,IDC_CUSTOM1,m_drawpad);

//}}AFX_DATA_MAP

}


Now,areyoureadyfortheaction???Then,pressCtrl+F5tocompileandexecutetheprogram.(Wishyouallthebest...Ithinkthereisnoerror!!!)
Donotforgettowrite
#include"MyCustomControl.h"
intheDialog'sHeaderfile,elseitwillgeneratetoomanyerrors.(IThinkyouwillnotblamemeHHAAHHAAHHAA).

Addingandprocessingthemessages

Aftersucceedinginthecriticalpartabove,youshouldgettheDialogboxcontainingthewhiterectangleonit.Thatisourcustomcontrol(BeliveMe!).That'sonlyasmallwindow.Now,wewillhavetoaddsomeWindows
messagestointeractwiththatcontrol.Readcarefully...
ToaddWindowsmessagestothewindow,rightclickontheclass
MyCustomControl
andselectAddWindowsMessageHandlertoaddthemessageslike,mousemove,clicketc...

Inthisway,afteralongwork(isit?),youhavecreatedyourowncustomcontrol.Nowrelax,andstartwritingyourown.Andpleaseratemyarticle(Ilikeit).Forexample,IhavewrittenasimpleDrawPadin
theincludedsourcecode.

Now,wewillgothroughashortsummaryofthisarticle:

Tocreatethecustomcontrol,wewillhavetodothefollowingthings:

CreateasimpleMFCApplicationcontainingDialogresource.
Selectthecustomcontrolformthecontrolbar.
DrawthecustomcontrolontheDialogresource.
RightclickthecustomcontrolandselecttheClassWizard.
FromAddclasspopup,addnewcustomclassselectingtheappropriatebaseclass.

AddthecodeandregistertheCustomWindowclass.
Addthemembervariableforabaseclass(customclass)inthedialog.

Setthecustomcontrol'sclasstotheregisteredwindowclassname.

Addthe
DoDataExchange
code.
Now,pressCtrl+F5tocompileandexecutetheapplication.
Add/EdittheWindowsmessagehandlersbyrightclickingtheCustomcontrol'sclassintheclassview.

Ifyoureallylikeit,thenmailmeatyogmj@hotmail.com,andmailmeyoursuggestionsandspellingMissssstakesinthisarticle.Alsoanybugsinthesource
code(asIamtheBugHunter{Ithinkso,Doyou?}).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐