c++builder - lesson 06_ messages and events of windows controls

13
 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls http://www.functionx.com/cppbuilder/Lesson06.htm 1/13  Messages and Events of Windows Controls  Messages Fundamentals  Introduction An application is made of various objects or controls. During the lifetime of the application, its controls regularly send messages to the operating system to do something on their behalf. These messages must be processed appropriately. Also, most of the time (in fact all the time), more than one application is (many processes are) running on the computer. The controls of a typical application send messages to the operating system. As the operating system is constantly asked to perform these assignments, because there can be so many requests presented unpredictably, it (the operating system) leaves it up to the controls to specify what they want, when they want it, and what behavior or result they expect. A message, like a letter you send to somebody, must provide a few pieces of information in order to be processed. For a Win32 application, these pieces of information are stored in a structure called MSG. It is defined as follows: typedef struct tagMSG {  HWND hwnd;  UINT message;  WPARAM wParam;  LPARAM lParam;  DWORD time;  POINT pt; } MSG, *PMSG;  For a Win32 application, each message is processed by a function called a window procedure. A window procedure is a pointer to function, therefore declared as CALLBACK, and it returns a positive 32-bit number. Therefore, a MSG variable must be passed to the window procedure for processing. In a Win32 application, a window procedure that processes a message requires 3 pieces of information with the last piece divided in two (which produces 4 pieces of information): The first piece of information must state WHO, that is, what control, sent the message The second piece of information must specify the name of the message: each Windows message is recognized by a name, which is simply a positive but constant numeric value The third and the fourth pieces carry information that depends on the message being sent Here is an example: //--------------------------------------------------------------------------- LRESULT CALLBACK WndProc(HWND hWnd,  UINT Msg,  WPARAM wParam,  LPARAM lParam) {  switch(Msg)  {  case WM_DESTROY:  PostQuitMessage(WM_QUIT);  break;  default:  return DefWindowProc (hWnd, Msg, wParam, lParam);  }  return 0; } //--------------------------------------------------------------------------- Once again, to make programming fast, the VCL provides its own message structure called TMessage and defined as follows: struct TMessage {  Cardinal Msg;

Upload: crickoff6109

Post on 03-Nov-2015

214 views

Category:

Documents


0 download

DESCRIPTION

Messages and Controls

TRANSCRIPT

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 1/13

    MessagesandEventsofWindowsControls

    MessagesFundamentalsIntroduction

    Anapplicationismadeofvariousobjectsorcontrols.Duringthelifetimeoftheapplication,itscontrols regularly sendmessages to theoperating system todo somethingon theirbehalf.These messages must be processed appropriately. Also, most of the time (in fact all thetime),morethanoneapplicationis(manyprocessesare)runningonthecomputer.

    Thecontrolsofatypicalapplicationsendmessagestotheoperatingsystem.Astheoperatingsystemisconstantlyaskedtoperformtheseassignments,becausetherecanbesomanyrequestspresentedunpredictably,it(theoperatingsystem)leavesituptothecontrolstospecifywhattheywant,whentheywantit,andwhatbehaviororresulttheyexpect.

    Amessage,likealetteryousendtosomebody,mustprovideafewpiecesofinformationinordertobeprocessed.ForaWin32application,thesepiecesofinformationarestoredinastructurecalledMSG.Itisdefinedasfollows:

    typedefstructtagMSG{ HWNDhwnd UINTmessage WPARAMwParam LPARAMlParam DWORDtime POINTpt}MSG,*PMSG

    ForaWin32application,eachmessageisprocessedbyafunctioncalledawindowprocedure.Awindowprocedure isapointertofunction,thereforedeclaredasCALLBACK,and itreturnsapositive32bitnumber.Therefore,aMSGvariablemustbepassedtothewindowprocedureforprocessing.

    In aWin32 application, a window procedure that processes amessage requires 3 pieces ofinformationwiththelastpiecedividedintwo(whichproduces4piecesofinformation):

    ThefirstpieceofinformationmuststateWHO,thatis,whatcontrol,sentthemessageThesecondpieceofinformationmustspecifythenameofthemessage:eachWindowsmessageisrecognizedbyaname,whichissimplyapositivebutconstantnumericvalueThethirdandthefourthpiecescarryinformationthatdependsonthemessagebeingsent

    Hereisanexample:

    //LRESULTCALLBACKWndProc(HWNDhWnd, UINTMsg, WPARAMwParam, LPARAMlParam){ switch(Msg) { caseWM_DESTROY: PostQuitMessage(WM_QUIT) break default: returnDefWindowProc(hWnd,Msg,wParam,lParam) } return0}//

    Once again, tomake programming fast, the VCL provides its ownmessage structure calledTMessageanddefinedasfollows:

    structTMessage{ CardinalMsg

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 2/13

    union { struct { WordWParamLo WordWParamHi WordLParamLo WordLParamHi WordResultLo WordResultHi } struct { intWParam intLParam intResult } }}

    A TMessage message must provide two pieces of information, as the TMessage structureshows: the name of the message and one group of information. Unlike the Win32 MSGstructure,inaVCLapplication,theobjectthatsendsthemessageisalreadyknown(becauseitis the one that sent themessage). The accompanying items of themessage are coded intoeitherthetoporthebottomstructuresoftheanonymousunion.Thetwoanonymousstructuresinsidetheunionindicatethatyouuseeitherthetoporthebottomstructurebutnotboth.

    Onceacontrolhascomposedamessage,itmustsendittotherighttarget,whichcouldbetheoperatingsystem.Inordertosendamessage,acontrolmustcreateanevent.Thecontrolisalsosaidtofireanevent.Tomakeadistinctionbetweenthetwo,amessage'snamewillusuallybewritteninuppercase.AnexamplewouldbeWM_MOVE,whichstandsfor"WindowMessageMove".ThenameofaneventusuallystartswithOn,whichindicatesanaction.

    Remember, the message is what needs to be sent. The event is the action of sending themessage.

    PracticalLearning:IntroducingMessages

    1. StartEmbarcaderoRADStudio2. Tocreateanapplication,onthemainmenu,clickFile>New>VCLFormsApplication

    C++Builder3. OntheToolPalette,expandtheStandardsection4. OntheToolPalette,doubleclickTButton

    5. ClicktheTEditcontrol6. Clickthecentertopsectionoftheform(noneedforprecision)

    AMapofMessagesAs mentioned already, the messages of a Win32 application are processed by a windowprocedure.ForaVCLapplication,youcanusethesameapproach.Alternatively,youcanuseatechniquereferredtoascreatingamapofmessages.

    For the compiler tomanagemessages, they should be listed in a public section of the classdefinition. The messages are included in a list referred to as a message map. The list ofmessages,that is, themessagemap,startswith theBEGIN_MESSAGE_MAPandendswiththe END_MESSAGE_MAP macros. The END_MESSAGE_MAP macro takes an argument,whichistheoriginalclassthatholdstheprimaryimplementationofthemessages.Hereisanexample:

    #ifndefStaticTextH#defineStaticTextH

    #include

    //classTStaticText:TGraphicControl{__published:

    private:

    public:

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 3/13

    BEGIN_MESSAGE_MAP

    END_MESSAGE_MAP(TGraphicControl)}//#endif

    BetweentheBEGIN_MESSAGE_MAPandtheEND_MESSAGE_MAPmacros,eachmessageisdeclared using either theMESSAGE_HANDLER or the VCL_MESSAGE_HANDLER macros.Theirsyntaxesare:

    MESSAGE_HANDLER(VCLMessageName,TMessage,EventName)VCL_MESSAGE_HANDLER(WindowsMsgName,VCLMessageName,EventName)

    Therearevariouscategoriesofmessagestheoperatingsystemreceives.Someofthemcomefrom thekeyboard, some from themouse,and someothers fromvariousother sources. Forexample, somemessages are sent by the application itself while some other messages arecontrolledbytheoperatingsystem.

    MessagesCharacteristicsThe most commonly sent messages have already been created in the objects of the VCLcontrols so much that you will hardly need to define new messages, at least not in thebeginning of your C++Builder programming adventure. Most of what youwill do consists ofimplementingthedesiredbehaviorwhenaparticularmessageissent.

    To start, you should know what messages are available, when, and how they work. Asmentionedalready,eachcontrolsendsitsownmessageswhennecessary.Basedonthis,somemessages are unique to some controls according to their roles. Some other messages arecommontovariouscontrols,astheytendtoprovidesimilaractions.Tomanagesuchvariousconfigurations, theVCL considers themessages in two broad categories. Those that take anargumentand those thatdonot.TheVCLdefineseventsas functionpointers (orpointers tofunction).

    Asithappens,somemessagesdonotrequiremuchinformationtobeperformed.Forexample,supposeyourheartsendsamessagetothearmandstates,Raiseyourhand.Inthiscase,supposeeverythingisalright,thearmdoesnotask,"howdoIraisemyhand?".Itsimplydoes.Thistypeofmessagewouldbesentwithoutanyaccompanyinginformation.Consideranothermessage where the arm carries somewater and says to themouth, "Swallow the followingwater".Themouthwouldneedthewaterthatneedstobeswallowed.Therefore,themessagemustbeaccompaniedbyadditionalinformation,whichisconsideredanargument.Consideronemoremessagewheretheheartsaystothetongue,Tastethefollowingfoodbutdonotswallowit.Inordertoprocessthismessage,thetonguewouldneedthefoodandsomethingtoindicatethatthefoodmustnotbeswallowed.Inthiscase,themessagemustbeaccompaniedbytwopiecesofinformation.

    To processmessages that do not require any additional argument, the VCL creates such aneventwith theTNotifyEvent type.Suchanevent isdeclaredasapointer to function in theclasses.hpplibraryasfollows:

    typedefvoid__fastcall(__closure*TNotifyEvent)(System::TObject*Sender)

    TheSenderargumentisthecontrolthatissendingthemessages.

    BesidesTNotifyEvent,theothereventscarrydifferentandappropriatenames.

    EventImplementationAlthoughtherearedifferentwaysyoucanimplementanevent,therearetwomainwaysyoucaninitiateitscoding.Ifthecontrolhasadefaulteventandifyoudoubleclickit,thecompilerwouldinitiatethedefaultevent.AnothertechniqueyoucanuseistoclicktheEventstaboftheObjectInspector.Thiswoulddisplayalistoftheeventsassociatedwiththeselectedcontrol:

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 4/13

    Thelistisdividedintwocolumns.Thenameofeacheventisdisplayedontheleftside.Youcanclickthenameofaneventtorevealacombobox.Ifasimilarevent(similareventsarethosethatshareabehavior)hasalreadybeenwritten,youcanclickthearrowofthecomboboxandselectitfromthelist:

    Otherwise, to initiate an event doubleclick the field on the right columnof thenameof thedesiredevent.

    Whenaneventhasbeeninitiated,youwouldbetransportedtotheCodeEditorandthecaretwouldbepositionedinthebodyoftheevent,readytoreceiveyourinstructions.Tocustomizeanevent,thecompilerdividesitsstructureinthreesections:

    //void__fastcallTForm1::FormMouseMove(TObject*Sender,TShiftStateShift,intX,intY){ //Writecodeassociatedwiththeeventhere}//

    Thecodingofaneventstartswith its returnvalue.Allevents inC++Builder returnvoid.Alleventsusethe__fastcallconvention.

    The return type is followedby thenameof theparent class fromwhere theeventwouldbefired.Thisismainlytheclassthatcontrolstheform.

    Afterthenameoftheclass,thecompilerrightlyusestheclassmemberaccessoperator(::)tocalltheevent,followingaC++rule.

    Thenameofanevent ismadeofacombinationofthecontrolthatownsorfiredtheeventandthenameoftheevent.

    Each event has at least one argument, the TObject *Sender. Some events use additionalargumentsthatwewillreviewwhencodingsuchevents.

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 5/13

    PracticalLearning:ImplementingEvents

    1. Doubleclickanunoccupiedareaoftheform2. Implementtheeventasfollows:

    //void__fastcallTForm1::FormCreate(TObject*Sender){MessageDlg(L"Theformhasbeencreated", mtConfirmation, TMsgDlgButtons()

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 6/13

    VK_F3 F3 VK_F4 F4VK_F5 F5 VK_F6 F6VK_F7 F7 VK_F8 F8VK_F9 F9 VK_F10 F10VK_F11 F11 VK_F12 F12VK_SCROLL ScrollLock VK_SNAPSHOT PrtScrn(Dependsonkeyboard)VK_PAUSE Pause/Break VK_TAB TabVK_BACK Backspace VK_CAPITAL CapsLockVK_SHIFT Shift VK_CONTROL CtrlVK_MENU Alt VK_ESCAPE EscapeVK_RETURN Enter VK_SPACE SpaceBarVK_INSERT Insert VK_HOME HomeVK_PRIOR PageUp VK_DELETE DeleteVK_END End VK_NEXT PageDownVK_UP UpArrowKey VK_RIGHT RightArrowKeyVK_DOWN DownArrowKey VK_LEFT LeftArrowKeyVK_LWIN LeftWindowsKey VK_RWIN RightWindowsKeyVK_APPS ApplicationsKey

    Thefollowingkeysapplytothenumerickeypad

    VK_NUMLOCK NumLock VK_NUMPAD0 0 VK_NUMPAD1 1VK_NUMPAD2 2 VK_NUMPAD3 3VK_NUMPAD4 4 VK_NUMPAD5 5VK_NUMPAD6 6 VK_NUMPAD7 7VK_NUMPAD8 8 VK_NUMPAD9 9VK_DIVIDE / VK_MULTIPLY *VK_SUBTRACT VK_ADD +VK_SEPARATOR VK_DECIMAL .

    Thereareactuallymorekeysthanthatbuttheabovearethemostfrequentlyused.

    TheVCLimplementskeyboardeventsusingtwofunctionpointers,TKeyEventandTKeyPressthatdependonthemessage.

    TheKeyDownMessageWhenakeyboardkeyispressed,amessagecalledWMKeyDown issent.WMKeyDown isaTKeyEventmessagethatproducestheOnKeyDownevent.Itssyntaxis:

    void__fastcallOnKeyDown(System::TObject*Sender,Word&Key,Classes::TShiftStateShift)

    TheKeyargumentspecifiesthekeythatwaspressed.TheOnKeyDown()eventcanbesentby any key. Alphabetic keys are represented by their character. For example, if the userpressesp,theKeyargumentwouldberepresentedas p. If theuserpressesakey, theKeyargumentwouldhavethevalueof.

    TheShift argument specifieswhether theShift, theCtrl, or theAlt keyswere pressedalongwiththeKeykey.ItisaPascalSetwhoseenumeratorhasthefollowingmembers:

    Value DescriptionssShift OneoftheShiftkeyswaspressedssAlt OneoftheAltkeyswaspressedssCtrl OneoftheCtrlkeyswaspressed

    Iftheuserpressestwokeysasanuppercase letter,suchR,theKeyargumentwouldhaveavalueofr.TheShiftargumentwouldbeusedtoindicatethattheShiftkeywasdownwhentheletterrwaspressed.

    PracticalLearning:SendingKeyDownMessages

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 7/13

    1. Ontheform,clickEdit12. ToexperimentwiththeWMKeyDownmessage,ontheObjectInspector,clicktheEventstab

    ifnecesary.DoubleclicktherightfieldofOnKeyDown

    3. DeletethelineofcodeintheEdit1Enterevent4. Implementtheeventasfollows:

    //

    #include#pragmahdrstop

    #include"Unit1.h"//#pragmapackage(smart_init)#pragmaresource"*.dfm"TForm1*Form1//__fastcallTForm1::TForm1(TComponent*Owner) :TForm(Owner){}//void__fastcallTForm1::FormCreate(TObject*Sender){ MessageDlg(L"Theformhasbeencreated", mtConfirmation, TMsgDlgButtons()

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 8/13

    void__fastcallOnKeyUp(System::TObject*Sender,Word&Key, Classes::TShiftStateShift)

    The Key argument specifies the key that was pressed. Like the OnKeyDown event, theOnKeyUpeventprocessesanykey.Alphabetickeysarerepresentedbytheircharacter.

    TheShiftargumentindicateswhethertheShift,theCtrl,ortheAltkeyparticipates inakeycombinationsuchasShift+$

    TheKeyPressMessageWhen the user presses a key, the WMKeyPress message is sent. Unlike the other twokeyboard messages, the key pressed for this event should (must) be a character key.WMKeyPressproducestheOnKeyPresseventwhosesyntaxis:

    void__fastcallOnLKeyPress(System::TObject*Sender,char&Key)

    TheKeyargumentmustbealetterorarecognizablesymbol.Lowercasealphabeticcharacters,digits,andthelowerbasecharacterssuchas,[]=/arerecognizedastheyare.Foranuppercaseletteroranupperbasesymbols,theusermustpressShift+thekey.Thecharacterwould be identified as one entity. This means that the symbol % typed with Shift + 5 isconsideredasonecharacter.

    PracticalLearning:SendingKeyPressMessages

    1. ToexperimentwiththeWMKeyPressmessage,ontheEventstaboftheObjectInspector,doubleclicktherightfieldofOnKeyPress

    2. DeletethecodeintheOnKeyDownevent3. ImplementtheOnKeyPresseventasfollows:

    //void__fastcallTForm1::Edit1KeyPress(TObject*Sender,char&Key){ switch(Key) { caseVK_RETURN: ShowMessage("YoupressedEnter") break caseVK_F1: ShowMessage("Helpisnotavailableatthemoment") break caseVK_DELETE: ShowMessage("Can'tDeleteThis") break case'k': ShowMessage("Lowercasekwaspressed") break case'K': ShowMessage("UppercaseKwaspressed") break case'$': ShowMessage("Showmethemoney") break }}//

    4. TesttheapplicationandpresstheDeleteortheF1keys.Noticethatnothinghappens5. Pressk

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 9/13

    6. ClickOKandpressShift+K7. ClosetheapplicationandreturnC++Builder

    MouseMessagesIntroductionThemouseisanotherobjectthatisattachedtothecomputerallowingtheusertointeractwiththemachine. Themouse and the keyboard can each accomplish some tasks that are not normallyavailableontheotherandbothcanaccomplishsometasksthesameway.

    Themouseisequippedwithtwo,three,ormorebuttons.Whenamousehastwobuttons,oneisusuallylocatedontheleftandtheotherislocatedontheright.Whenamousehasthreebuttons,one is in themiddle of the other two. Themouse is used to select a point or position on thescreen.Once the user has located an item,which could also be an empty space, a letter or aword,heorshewouldpositionthemousepointeronit.Toactuallyusethemouse,theuserwouldpresstheleft,themiddle(ifany),ortherightbutton.Iftheuserpressestheleftbuttononce,thisactioniscalledClick.Iftheuserpressestherightmousebutton,theactionisreferredtoasRightClick.Iftheuserpressestheleftbuttontwiceandveryfast,theactioniscalledDoubleClick.

    MouseeventsareimplementedasTMouseEventandTMouseMoveEventfunctionpointers.

    TheMouseDownMessageImaginetheuserhaslocatedapositionoranitemonadocumentandpressesoneofthemousebuttons.Whilethebuttonispressedandisdown,abuttondownmessageissent.Thesyntaxofthiseventisasfollows:

    void__fastcallOnMouseDown(System::TObject*Sender,TMouseButtonButton, Classes::TShiftStateShift,intX,intY)

    TheButtonargumentspecifieswhatbuttonwasclicked.ThebuttonsofthemouseareidentifiedbytheTMouseButtonenumeratorwhosemembersare:

    Value DescriptionmbLeft TheleftmousebuttonwasclickedmbRight TherightmousebuttonwasclickedmbMiddle Themiddlemousebuttonwasclicked

    TheShiftargumentindicateswhethermousebuttonand/orakeyboardkeywas/werepressedandhelddownwhentheButtonwasclicked.Itcanhaveoneofthefollowingvalues:

    Value DescriptionssShift OneoftheShiftkeyswaspressedssAlt OneoftheAltkeyswaspressedssCtrl OneoftheCtrlkeyswaspressedssLeft TheleftmousebuttonwashelddownssRight Therightmousebuttonwashelddown

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 10/13

    ssMiddle Themiddlemousebuttonwashelddown

    ssDouble TheButtonwasdoubleclicked

    TheXandtheYargumentrepresenttheTPoint(X,Y)pointwherethemousewasclicked.

    PracticalLearning:SendingaMouseDownMessage

    1. Displaytheform2. Toexperimentwiththemousedowneffect,ontheEventstaboftheObjectInspector,double

    clicktherightsideoftheOnMouseDownfield3. Implementtheeventasfollows:

    //void__fastcallTForm1::FormMouseDown(TObject*Sender,TMouseButtonButton, TShiftStateShift,intX,intY){ShowMessage("Mouseat("+IntToStr(X)+","+IntToStr(Y)+")")}//

    4. Testtheprogramandclickvariouspartsoftheform5. Closeitandreturntoyourprogrammingenvironment

    TheMouseUpMessage

    Afterpressingamousebutton,theuserusuallyreleasesit.Whilethebuttonisbeingreleased,abuttonupmessageissentanditdependsonthebutton,leftorright,thatwasdown.TheeventproducedisOnMouseUp.

    TheOnMouseUpeventuses thesamesyntaxas theOnMouseDown eventandprocesses thesamearguments.

    TheMouseMoveMessageWheneverthemouseispositionedandbeingmovedontopofacontrol,amouseeventissent.ThiseventisimplementedasaTMouseMoveEventfunctionpointeranditssyntaxis:

    void__fastcallOnMouseMove(System::TObject*Sender, Classes::TShiftStateShift,intX,intY)

    TheShiftargument is thesameas theothermousemessages.TheXandYvalues identify thelocationofthemouseatthetimethiseventfires.

    ProgrammerDefinedMessagesIntroductionThe list of methods and messages available for the objects used in your applications is veryimpressivebecausetheVCLtriestohelpprocessasmanymessagesaspossible.Unfortunately,insomeareas,theVCLtendstoaddressonlythemostcommonlyusedmessages,whichisstillverylong,aswewillseethroughoutourlessons.

    TheWin32libraryprovidesmoremessagesthantheVCLimplements.Normally,youshouldfirstcheckifamessageyouwanttoprocessisalreadyavailableforyourcontrol.Ifitisnot,youcancreateyour ownmessage and its event.Once again you have various options. If themessagebelongs to, ormust be processed by, a form, you can create it in the header file of the form.Otherwise,youcancreateanewcontrolbysimplyderivingaclassfromanexistingcontrol.

    WindowsFunctionsAnotherwayyouwillmanipulatecontrolsconsistsofcallingaWin32APIfunction.Therearetwomaincategoriesoffunctionsyouwillcall: thosethatmust identifythecontrol that iscallingthefunctionandthosethatdonot.Ifthefunctionrequiresthecontrolthatcalledit,youcanspecifythecontrolusingitshandle.Ifthefunctiondoesnotneedthispieceofinformation,thenyoucanomitit.Wewillseevarioustypesofbothcategoriesoffunctions.

    Mostof themessageswewilluse inourapplicationsare implemented invariousclassesof theVCL.Someothersarenot.SomeofthemessagesareavailableintheWin32libraryandyoucanusetheminyourapplication.This ismadepossiblebycallingtheSendMessage()function. Itssyntaxis:

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 11/13

    LRESULTSendMessage(HWNDhWnd,UINTMsg,WPARAMwParam,LPARAMlParam)

    ThehWndargumentistheobjectorcontrolthatissendingthemessage.

    TheMsgargumentisthemessagetobesent.

    ThewParamandthelParamvaluesdependonthemessagethatisbeingsent.

    The advantage of using the SendMessage() function is that, when sending this message, itwouldtargettheprocedurethatcanperformthetaskandthisfunctionwouldreturnonlyafteritsmessagehasbeenprocessed.Becausethisfunctioncansometimesuniversallybeused,thatisbyalmost any control or object, the application cannot predict the type of message thatSendMessage() iscarrying.Therefore,(theprobabledisadvantage is that)youmustknow the(nameoridentityofthe)messageyouaresendingandyoumustprovideaccurateaccompanyingitems.

    HereisanexamplethatchangesthecaptionofaformusingtheWM_SETTEXTmessage:

    //void__fastcallTForm1::FormCreate(TObject*Sender){ constchar*Msg="Thismessagewassent" SendMessage(Handle,WM_SETTEXT,0,(LPARAM)(LPCTSTR)Msg)}//

    PerformingMessagesBesidestheSendMessage() function, theTControlclassprovidesthePerform()method thatallowsyoutosendamessageanytime.Itssyntaxis:

    int__fastcallPerform(unsignedMsg,intWParam,intLParam)

    TheTControl::Perform()methodfunctionsliketheSendMessage()functionexceptthat,sinceit isaVCLfunction, itomitsthehandletothecontrolbecausethecontrolthatcalls itwouldbespecified already. The first argument, Msg, is the identifier of the message that needs to beprocessed. It is exactly like the second argument of the SendMessage() function. Like theSendMessage()function,thevaluesofWParamandLParamdependonthemessage.Hereisanexampleusedtocloseaform:

    //void__fastcallTForm1::Button1Click(TObject*Sender){ Perform(WM_CLOSE,0,0)}//

    CustomMessageImplementationTocustomizeanexistingmessageofacontrolortocreateanewmessagethatisnotavailableforyourcontrol,theTControlclassprovidestheWndProc()method.Itssyntaxis:

    virtualvoid__fastcallWndProc(Messages::TMessage&Message)

    Inordertousethismethod,youmustoverrideitinyourownclass.Hereisanexample:

    //classTForm1:publicTForm{__published://IDEmanagedComponentsprivate://Userdeclarationspublic://Userdeclarations __fastcallTForm1(TComponent*Owner) virtualvoid__fastcallWndProc(TMessage&Msg)}//

    TheMessageargumentisanymessageyouwanttoprocess.AsdoneforaWin32application,theMessagevalueistypicallypassedtoaswitchconditionandeachdesiredmessageistreatedinacase statement. After processing the messages and before closing the member function, youshould (must) call the parent class to process themessages thatwere not treated. Here is anexample that treats theWM_MOVEmessageandprevents theuser frommoving the form (bypreventingthemousefromcapturingthetitlebar):

    //void__fastcallTForm1::WndProc(TMessage&Message){ switch(Message.Msg)

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 12/13

    { caseWM_MOVE: ReleaseCapture() break }

    TForm::WndProc(Message)}//

    Aftercreatingthemessage, if it is intended for the form to treat, themessage is readyand itseventwouldfireappropriately.Iftheevent is foraparticularcontrol,youmust letthecompilerknowthatyouhaveawindowprocedurethatwouldprocessaparticularmessageorthemessagesofacertaincontrol.Todothis,youcanassignWndProctothecontrolsWindowProcmembervariable.ThiscouldbedoneintheconstructorortheOnCreate()eventoftheformasfollows:

    //__fastcallTForm1::TForm1(TComponent*Owner) :TForm(Owner){ this>WindowProc=WndProc}//

    Aswementionedearlier, insteadofusingawindowprocedure, you can createamessagemapthatliststheevent(s)thatyouwanttofire.Makesureyoualsodeclarethefunctionthatwillcarrytheevent:

    //

    #ifndefUnit1H#defineUnit1H//#include#include#include#include//classTForm1:publicTForm{__published: //IDEmanagedComponentsprivate: //Userdeclarationsvoid__fastcallTForm1::DontMoveMe(TObject*Sender)public: //Userdeclarations__fastcallTForm1(TComponent*Owner)

    BEGIN_MESSAGE_MAPVCL_MESSAGE_HANDLER(WM_MOVE,TObject*,DontMoveMe)END_MESSAGE_MAP(TForm)}//externPACKAGETForm1*Form1//#endif

    Afterdoingthisintheheaderfile,inthesourcefile,implementthemethodasyouseefit.Hereisanexample:

    //

    #include#pragmahdrstop

    #include"Unit1.h"//#pragmapackage(smart_init)#pragmaresource"*.dfm"TForm1*Form1//__fastcallTForm1::TForm1(TComponent*Owner) :TForm(Owner){}//void__fastcallTForm1::DontMoveMe(TObject*Sender){ ReleaseCapture()}

  • 2/9/2015 C++Builder - Lesson 06: Messages and Events of Windows Controls

    http://www.functionx.com/cppbuilder/Lesson06.htm 13/13

    //

    MethodsandMessagesCombinationsTheevents ofWindows controls aredesigned tobe executed at specific periods in response tosomeoccurrence.Forexample,onlywhentheuserpressesamousebuttoncanamessagerelatedtothisactionwouldoccur.Yet,oneofthemostinfluentialwaysofcreatinganeffectiveprogramistoanticipateusersactionsasmuchaspossible.Thisallowsyoutocorrectlyrespond.Tosupportthisidea,theVCLprovidesasystemofcombiningcontrolsmessagesandtheirassociatedevents.

    Whentheuserinitiatesanactiontosendamessage,thecontrolthatownstheactionsendsthemessageandanaccompanyingmethod.Thismethod,althoughbelonging to the control, allowsothercontrolsorotherpartsoftheprogramtoaccesstheeventasiftheycontrolledwhensuchaneventwouldoccur.Forexample, if theuser clicksa control, thecontrol composesand sendsaclickmessage.BecausethecontrolisalsoequippedwithaClick()method,anothercontroloftheapplicationcancallitsClick()eventandperformthesameaction.Hereisanexample:

    //void__fastcallTForm1::Button1Click(TObject*Sender){ Perform(WM_CLOSE,0,0)}//void__fastcallTForm1::Panel1MouseDown(TObject*Sender, TMouseButtonButton,TShiftStateShift,intX,intY){ Button1>Click()}//

    PracticalLearning:EndingtheLesson

    1. Toendthelesson,onthemainmenu,clickFile>Exit2. Whenaskedwhetheryouwanttosave,clickNo

    Previous Copyright20102011FunctionX,Inc. Next