Creating and Using custom controlsin VC++
2012-04-22 08:52
417 查看
CreatingandUsingcustomcontrolsinVC++
Introduction
Hithere!ThisismyfourtharticleforTheCodeProject.MigratingtowardstheVC++,IhavefirstlyconcernedwiththecustomcontrolsthatcanbecreatedwiththehelpofVC++,sincethatisaveryhelpfulfeaturewhenyouwanttomodifythecontentsofanycontroloryouwanttocreateyourown.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
CWndclass
asabaseclass.
Andfinally,youhavecreatedaclassforyourcontrol.Now,theseriouspartbegins....
Astheclasshasbeencreatedbyusingthe
CWndasabase,wewillhavetoregisterthisclasssincethisisacustomclass.So,wewillhavetowritethefunction
RegisterWndClass()to
dothat.Itmaybecodedasbelow...
Collapse|
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|
MyCustomControl::MyCustomControl()
{
//RegisterMywindowclass
RegisterWndClass();
}
Ithinkanyonewillthinkwhatis
MYWNDCLASS.Theansweristhatitisthedefinedclassnameforourcustomclass.ItisdefinedatthetopoftheMyCustomControl.hfileas
follows:
Collapse|
#defineMYWNDCLASS"MyDrawPad"
Now,wehaveourownclasscalled
MyDrawPad.
AttachingClasstotheCustomControl:
Withallthingsgoingright,weareapproachingtowardscompletingthecreationofthecustomcontrol.Thelastthingremainingistosetthecustomcontrolasourcreatedwindowclass.Forthat,rightclickonthecustomcontrolintheresourceviewandthenselectthepropertiesofthecustomcontrol.Thedialogboxwillappearasshownbelow...
Then,settheclassnameas
MyDrawPadthatwehavecreatedearlier.Hereyoucanselectthewindowstylebychangingthehexadecimalvalueinthestyleeditbox.
Ihaveexperimentedwithsomeofthevalues,youcanalsotrythem.
DoingtheDataExchange
Now,allthethingsaresetup.Butthedatamustbeexchangedbetweenthewindowandourapplication.So,addavariableforourcustomcontroltoyourdialogclassasfollows:Collapse|
//Implementation
protected:
HICONm_hIcon;
MyCustomControlm_drawpad;//Thisisourcustomcontrol
Afterthat,youhavetoaddthefollowingcodeinthe
DoDataExchage()functiontointeractwiththecustomcontrol.
Collapse|
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,wewillhavetoaddsomeWindowsmessagestointeractwiththatcontrol.Readcarefully...
ToaddWindowsmessagestothewindow,rightclickontheclass
MyCustomControlandselectAddWindowsMessageHandlertoaddthemessageslike,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
DoDataExchangecode.
Now,pressCtrl+F5tocompileandexecutetheapplication.
Add/EdittheWindowsmessagehandlersbyrightclickingtheCustomcontrol'sclassintheclassview.
Ifyoureallylikeit,thenmailmeat
code(asIamtheBugHunter{Ithinkso,Doyou?}).
相关文章推荐
- custom control的使用方法(Creating and Using custom controls in VC++)
- Creating custom headers and footers in Application level events using global.asax
- Creating custom headers and footers in Application level events using global.asax
- Neat Stuff to Do in List Controls Using Custom Draw
- Animating Views Using Scenes and Transitions ? - Creating Custom Transitions
- 创建和使用范围(Creating and Using Ranges)CFString in Core Foundation
- Neat Stuff to Do in List Controls Using Custom Draw
- Building a WPF Sudoku Game: Part 4 - Building a Least Privilege Plug-in System and Even More Custom Controls
- Creating Vista Gadgets: Using HTML, CSS and JavaScript with Examples in RSS, Ajax, ActiveX (COM) and
- Creating custom and compound views in Android - Tutorial
- GDI+ Programming: Creating Custom Controls Using C#
- Creating and Using a New Content Type in SharePoint 2007(zhuan:http://www.sharepointproconnections.com/article/sharepoint-portal
- Building a WPF Sudoku Game: Part 4 - Building a Least Privilege Plug-in System and Even More Custom Controls (zz)
- Creating Custom Annotations and Using Them
- Creating CustomBinding for WCFBasicHTTP for SSL and BasicAuthentication in BizTalk 转载自:http://geekswithblogs.net/mipsen
- Pro .NET 2.0 Windows Forms and Custom Controls in VB 2005
- Pro .NET 2.0 Windows Forms and Custom Controls in C#
- Embedding and retrieving resources in custom controls
- SQL Server Database Mirroring - Creating and using Mirror Endpoints in Principal, Mirror and Witness
- XAF How to show custom forms and controls in XAF (Example)