Beruflich Dokumente
Kultur Dokumente
PublishedJun23,2015LastupdatedApr14,2017
BuildingaWin32App,Part2:WindowsandMessages
Purpose
ThepurposeofthistutorialistotakeadeeperlookattheWinMainfunctioninordertounderstandhowstructuredaWin32applicationis.Bytheendofthistutorial,readers
shouldbeabletounderstandtheconceptsofmessagequeues,windowregistration&creation,aswellasthebaseofmessageloopandhowalltheseoperatetomakean
applicationwork.
Readpartonehere.
IntendedAudience
ThistutorialrequiresbasicknowledgeofVisualStudio,proficiencyinC/C++,asthistutorialdoesnotcovertheC++programminglanguage.
Objectives
Demestifythemainfunction.
Windowregistration&creationanalysis.
Understandingthemessageloop.
Analyzingwindowprocedure.
WindowsGraphicalEnvironment
Inthewindowsgraphicalenvironment,everythingisawindow.Eventhedesktopareaispartofawindow.Thiswindowismorepreciselyknownasthedesktopwindow.
Everytimeyourunanapplicationthatdisplaysoneormorewindows,allofit'swindowsbecomechildrenofthedesktopwindow.
MarcAntoineLortie
(Currentlyunavailable)Freetips/help/codereview,seefieldsspecifiedbelow
Follow
SIGNUP
https://www.codementor.io/malortie/buildwin32apiappwindowsmessagesccppvisualstudiodu107sbya 1/9
06/05/2017 BuildingaWin32App,Part2:WindowsandMessages|Codementor
AnOverviewofWinMain
Declaration
Thisisthemainfunction.Let'sanalyzeit'stypesignature
intAPIENTRY_tWinMain(
_In_HINSTANCEhInstance,
_In_HINSTANCEhPrevInstance,
_In_LPTSTRlpCmdLine,
_In_intnCmdShow
);
Thefirstparameter,hInstance,representstheactualinstanceofanapplication.
Thesecondparameter,hPrevInstance,isahandletoapreviousinstance,(suchinstanceonlyexistsifthereisanalreadyrunningapplicationofthesameapplication).
Thirdparameter,lpCmdLine,representsthecommandlinearguments.
Finally,nCmdShowisavaluethattellshowthewindowshouldbedisplayed.Forexample,ifthedisplayissettobeminimized,thisvaluewillbe2.Ifthewindowneedsto
showasmaximized,thisvaluewillbe3,etc.
HereisaschematicthatdemonstratesthemaindifferencesbetweenhInstanceandhPrevInstance.
Definition
Then,comesthedefinitionofWinMain.
intAPIENTRY_tWinMain(_In_HINSTANCEhInstance,
_In_opt_HINSTANCEhPrevInstance,
_In_LPTSTRlpCmdLine,
_In_intnCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
//TODO:Placecodehere.
MSGmsg;
HACCELhAccelTable;
//Initializeglobalstrings
LoadString(hInstance,IDS_APP_TITLE,szTitle,MAX_LOADSTRING);
LoadString(hInstance,IDC_INTRODUCTION,szWindowClass,MAX_LOADSTRING);
MyRegisterClass(hInstance);
//Performapplicationinitialization:
if(!InitInstance(hInstance,nCmdShow))
{
returnFALSE;
}
hAccelTable=LoadAccelerators(hInstance,MAKEINTRESOURCE(IDC_INTRODUCTION));
MarcAntoineLortie
(Currentlyunavailable)Freetips/help/codereview,seefieldsspecifiedbelow
//Mainmessageloop:
while(GetMessage(&msg,NULL,0,0))
Follow
{
SIGNUP
https://www.codementor.io/malortie/buildwin32apiappwindowsmessagesccppvisualstudiodu107sbya 2/9
06/05/2017 BuildingaWin32App,Part2:WindowsandMessages|Codementor
if(!TranslateAccelerator(msg.hwnd,hAccelTable,&msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return(int)msg.wParam;
}
Ibelieveyouarecurrentlyaskingyourself,"ShouldIhavetomemorizeallthis?","Isitthehelloworldprogramatit'ssimplestform?".Simplycalmdown.Thisreallyisnot
theminimalisthelloworldprogram.Bydefault,whenyouchoosetostartfromaWin32applicationtemplate,itwillcreatevariousresourcessuchasdialogs,andstring
tables.
Letusbeginwiththetwofirstlines.
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETERisasimplemacrotopreventthecompilerfromgeneratingwarnings,duetounusedvariables.Sinceanapplicationdoesnotneedtospecify
commandlinearguments(lpCmdLine)orwaystoshowthewindow(nCmdShow),thesevariablesmayornotbeused,thus,unreferenced,whichleadstoaminor/harmless
memorywaste.
Thenexttwolines,aresimpledeclarations.Theirusewillbeexplainedlaterthroughoutthistutorial.
MSGmsg;
HACCELhAccelTable;
AlwaysinWinMain,thesenextthreefunctions.
LoadString(hInstance,IDS_APP_TITLE,szTitle,MAX_LOADSTRING);
LoadString(hInstance,IDC_INTRODUCTION,szWindowClass,MAX_LOADSTRING);
MyRegisterClass(hInstance);
LoadStringisafunctionusedtoretrieveastringresourcefromaspecifiedinstance.Astringresourcecanrepresentlanguagetranslation/windowtitle/messageboxlabels,
etc.Onceretrieved,thestringiscopiedtoadestinationbuffer,szTitleandszWindowClassinthiscase.
MyRegisterClassisatemplatedefinedfunctionthatregisterstheclassoftheapplication.Wewillcoverthisfunctionatthenextstep.
AsforInitInstance,thistemplatedefinedfunctionissimplyusedtocreateandinitializethewindow.
if(!InitInstance(hInstance,nCmdShow))
{
returnFALSE;
}
ThefunctionLoadAcceleratorsisusedtoretrieveakeyboardacceleratorfromaresourcefile.Iwillnotdescribeit'susehere,asitwillbecoveredinfuturetutorials.
hAccelTable=LoadAccelerators(hInstance,MAKEINTRESOURCE(IDC_INTRODUCTION));
Finally,themessageloop.
while(GetMessage(&msg,NULL,0,0))
{
if(!TranslateAccelerator(msg.hwnd,hAccelTable,&msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return(int)msg.wParam;
Themessageloopisresponsiblefordispatchingmessagesfromthemessagequeuetotheappropriatewindow,asWin32APIusesaneventdrivenarchitecture.The
application'sexitcodeisstoredinastructureMSGandreturned.
WindowRegistration
Beforeawindowcanbecreated,itneedstoberegisteredinordertobeidentifiedduringruntimebymessagesandevents.Inordertounderstandtheregistrationprocess,
let'sheadtoMyRegisterClassdefinition.
//
//FUNCTION:MyRegisterClass()
//
//PURPOSE:Registersthewindowclass.
//
ATOMMyRegisterClass(HINSTANCEhInstance)
{
WNDCLASSEXwcex;
MarcAntoineLortie
wcex.cbSize=sizeof(WNDCLASSEX);
(Currentlyunavailable)Freetips/help/codereview,seefieldsspecifiedbelow
wcex.style =CS_HREDRAW|CS_VREDRAW;
Follow
wcex.lpfnWndProc =WndProc;
SIGNUP
https://www.codementor.io/malortie/buildwin32apiappwindowsmessagesccppvisualstudiodu107sbya 3/9
06/05/2017 BuildingaWin32App,Part2:WindowsandMessages|Codementor
wcex.cbClsExtra =0;
wcex.cbWndExtra =0;
wcex.hInstance =hInstance;
wcex.hIcon =LoadIcon(hInstance,MAKEINTRESOURCE(IDI_INTRODUCTION));
wcex.hCursor =LoadCursor(NULL,IDC_ARROW);
wcex.hbrBackground =(HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName =MAKEINTRESOURCE(IDC_INTRODUCTION);
wcex.lpszClassName =szWindowClass;
wcex.hIconSm =LoadIcon(wcex.hInstance,MAKEINTRESOURCE(IDI_SMALL));
returnRegisterClassEx(&wcex);
}
Toregisterawindow,wemustbeginbydefiningthewindowclassattributes.Theseareattributestobesharedbyallwindowsthatwillusethiskindofclass.Itisimportant
tonotethatawindowclassmustbeunique.
TheWNDCLASSEXstructure
typedefstructtagWNDCLASSEXW{
UINTcbSize;
/*Win3.x*/
UINTstyle;
WNDPROClpfnWndProc;
intcbClsExtra;
intcbWndExtra;
HINSTANCEhInstance;
HICONhIcon;
HCURSORhCursor;
HBRUSHhbrBackground;
LPCWSTRlpszMenuName;
LPCWSTRlpszClassName;
/*Win4.0*/
HICONhIconSm;
}WNDCLASSEXW,*PWNDCLASSEXW,NEAR*NPWNDCLASSEXW,FAR*LPWNDCLASSEXW;
Name Description
cbSize ThesizeinbytesofWNDCLASSEX
style Thestyleofthewindow
lpfnWndProc ApointertoaWNDPROCcallbacktouseasamessagelistener
cbClsExtra Asetofadditionalflagvalues
cbWndExtra Asetofadditionalflagvalues
hInstance Ahandletothecurrentapplicationinstance
hIcon Ahandletoanicon
hCursor Ahandletoacursor
hbrBackground Ahandletoabrushcolor
lpszMenuName TheMenuname
lpszClassName Thiswindow'sclassname
*Reminder*
WindowsDatatypes
Name Definition
LPSTR typedefchar*LPSTR
LPCSTR typedefconstchar*LPCSTR
LPWSTR typedefwchar_t*LPWSTR
LPCWSTR typedefconstwchar_t*LPCWSTR
PVOID typedefvoid*PVOID
HANDLE typedefPVOIDHANDLE
HINSTANCE typedefHANDLEHINSTANCE
RegisterClassEx
returnRegisterClassEx(&wcex);
RegisterClassExisafunctionthattakesapointertoaWNDCLASSEXstructureandreturnsauniqueidentifierforthewindow.Ifthefunctionfails,thereturnvalueiszero.
ReasonswhyRegisterClassExwouldnotwork
cbSizeisnotspecifiedorimproperlyinitialized.TherecommendedwayistosetcbSizetosizeof(WNDCLASSEX).
lpszClassNameisalreadyregistered,andthusiscausingafailuretoavoidduplicateclasses.
hInstanceisnotavalidapplicationinstance,orisuninitialized.
hbrBackgroundisaninvalidHANDLEvalue.ThedefaultvalueisCOLOR_WINDOW+1.
Windowcreation
MarcAntoineLortie
Afterthewindowregistration,thewindowneedstobecreated.LetusproceedtothefunctionInitInstance.
(Currentlyunavailable)Freetips/help/codereview,seefieldsspecifiedbelow
Follow
//
SIGNUP
//FUNCTION:InitInstance(HINSTANCE,int)
https://www.codementor.io/malortie/buildwin32apiappwindowsmessagesccppvisualstudiodu107sbya 4/9
06/05/2017 BuildingaWin32App,Part2:WindowsandMessages|Codementor
//
//PURPOSE:Savesinstancehandleandcreatesmainwindow
//
//COMMENTS:
//
//Inthisfunction,wesavetheinstancehandleinaglobalvariableand
//createanddisplaythemainprogramwindow.
//
BOOLInitInstance(HINSTANCEhInstance,intnCmdShow)
{
HWNDhWnd;
hInst=hInstance;//Storeinstancehandleinourglobalvariable
hWnd=CreateWindow(szWindowClass,szTitle,WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,0,CW_USEDEFAULT,0,NULL,NULL,hInstance,NULL);
if(!hWnd)
{
returnFALSE;
}
ShowWindow(hWnd,nCmdShow);
UpdateWindow(hWnd);
returnTRUE;
}
ThisvariablehWnd,isahandletoourmainwindow.itisinitializedbyCreateWindow,whichisusedtocreateawindowofaparticularstyleatagivenposition.Ifawindow
parentisspecified,thenewlycreatedwindowwillbecomeachildoftheparent.
AllpresentparametersinCreateWindowarethesameasthosefoundinCREATESTRUCT.
Hereisacloserlookatthisparticularstructure.
TheCreateStructStructure
typedefstructtagCREATESTRUCTA{
LPVOIDlpCreateParams;
HINSTANCEhInstance;
HMENUhMenu;
HWNDhwndParent;
intcy;
intcx;
inty;
intx;
LONGstyle;
LPCSTRlpszName;
LPCSTRlpszClass;
DWORDdwExStyle;
}CREATESTRUCTA,*LPCREATESTRUCTA;
Name Description
lpCreateParams AnargumentthatcanbepassedforfurtheruseintheWndProcfunction
hInstance Theinstanceoftheassociatedapplication
hMenu Ahandletoamenu
hwndParent Ahandletoawindowtouseasparent
cy Theheightofthewindow
cx Thewidthofthewindow
x Theleftpositionofthewindow
y Thetoppositionofthewindow
style Thestyleofthewindow
lpszName Thenameofthewindow(title)
lpszClass Thewindow'sclassname.Thismustmatchwcex.lpszClassNameinWNDCLASSEX
dwExStyle AnextendedwindowstyleUnusedinthisexample!
Acceleratortable
Thisinstructionisusedtoloadanacceleratortablefromaresourcefile.
hAccelTable=LoadAccelerators(hInstance,MAKEINTRESOURCE(IDC_INTRODUCTION));
Iwillnotexplainindepthresourcefiles,asresourceswillbeexplainedinfurthertutorials,butforaquickoverview:Anacceleratortableisusedtobindkeyboard
combinationstoapplicationcommands.
Bydefault,templateapplicationsuseautomaticallygeneratedacceleratortables,butkeepinmindthatthesearenotrequiredatall.
TheMessageLoop
Nowthatthemainwindowiscreatedandsetup,itistimetosetupthemainloopofourapplication,whichwilltakecareofprocessingmessagesandevents.Before
demonstratingthecode,wewilltakealookattheconceptofsendingandrecievingeventsinaneventdrivenarchitecture.
MarcAntoineLortie
(Currentlyunavailable)Freetips/help/codereview,seefieldsspecifiedbelow
Follow
SIGNUP
https://www.codementor.io/malortie/buildwin32apiappwindowsmessagesccppvisualstudiodu107sbya 5/9
06/05/2017 BuildingaWin32App,Part2:WindowsandMessages|Codementor
Tobeginwith,thesystemchecksiftherearependingmessagesinthemessagequeue.Ifsuchaconditionismet,thenthesystemtranslatesanddispatchesthemessagetothe
appropriatewindow,whichis,inthiscase,ourmainwindow.Eachwindowisgivenaprocedure.ThisprocedureisrepresentedbylpfnWndProcintheWNDCLASSEX
structure.Thisprocedureiscalledbywiththewindowhandletowhichitisassociated,themessagetype,andadditionally,withuptotwoparameters,wParam,lParam.The
windowprocedureisresponsiblefordoingtasks,oftenbasedonthemessagetype.Ifthemessagetypeisthequitmessage,thefunctionwillreturnwithnegativeresult,
causingthemessagelooptoend.Ifthismessagediffersfromquitting,thenthesystemwillreturntothemessagequeuetoprocessthenextmessage,orwaituntilitreceives
newnotifications.
Inordertoprocessmessagescontinuously,weneedtocreatealoop.Thisloop,calledthemessageloop.HereisthecodefromWinMain.
//Mainmessageloop:
while(GetMessage(&msg,NULL,0,0))
{
if(!TranslateAccelerator(msg.hwnd,hAccelTable,&msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
GetMessage
BOOLWINAPIGetMessage(
_Out_LPMSGlpMsg,
_In_opt_HWNDhWnd,
_In_UINTwMsgFilterMin,
_In_UINTwMsgFilterMax
);
TheGetMessagefunctionisusedtoretrievependingmessagesinthemessagequeue,waitingforaparticulareventtooccur,suchasmouseclicks,windowresizing,focus
loss,etc.
TranslateAccelerator
intWINAPITranslateAccelerator(
_In_HWNDhWnd,
_In_HACCELhAccTable,
_In_LPMSGlpMsg
);
Asitrecievesamessage,thefunctionTranslateAcceleratorisusedtodeterminewhetherthismessagewastriggeredbyanacceleratorhandle.Ifthisisthecase,thenthe
acceleratorwillhandlethemessageitselfandredirectittothepropercommands.
TranslateMessage
BOOLWINAPITranslateMessage(
_In_constMSG*lpMsg
);
Iftheapplicationneedstoreadfromuserinputsuchaskeyboard/mouse,TheTranslateMessagefunctionisusedtranslatevirtualkeymessagesintocharactermessages.
DispatchMessage
LRESULTWINAPIDispatchMessage(
_In_constMSG*lpmsg
);
Thisfunction,DispatchMessage,isusedtodispatchmessagestoawindowprocedure.Inthiscase,thewindowprocedureisrepresentedbyattributelpfnWndProcfrom
WNDCLASSEX,WndProc.
Message&Eventcallback
Thisisthewindowprocedure,whichiscalledwhenaparticulareventissentthiswindow.Tobeginwith,letushavealookatthefunction'sdeclarationandparameters.
LRESULTCALLBACKWindowProc(
HWNDhwnd,
UINTmessage,
WPARAMwParam,
LPARAMlParam
);
Name Description
hwnd Ahandletothewindowitself
message Asystemdefinedmessage
wParam Amessageparameter
lParam Amessageparameter
Thefirstparameter,hwnd,representsthecurrentwindowbeingprocessed.ThisisrepresentedbyhwndintheInitWindow.
Thesecondparameter,message,isasystemdefinedmessage.Thisisusedtodeterminethenatureoftheevent,.i.e:Keyboardinput,mouseinput,windowfocus
acquisition/loss,etc.
TheremainingparameterswParam&lParamaremessageparametersthatmaycontaindata/valuesbasedonthecurrentvalueofmessage,themessagetype.
MarcAntoineLortie
(Currentlyunavailable)Freetips/help/codereview,seefieldsspecifiedbelow
Nowitistimetoexaminethedefinitionof
Follow WndProc,thewindowprocedurefunction.
SIGNUP
https://www.codementor.io/malortie/buildwin32apiappwindowsmessagesccppvisualstudiodu107sbya 6/9
06/05/2017 BuildingaWin32App,Part2:WindowsandMessages|Codementor
//
//FUNCTION:WndProc(HWND,UINT,WPARAM,LPARAM)
//
//PURPOSE:Processesmessagesforthemainwindow.
//
//WM_COMMAND processtheapplicationmenu
//WM_PAINT Paintthemainwindow
//WM_DESTROY postaquitmessageandreturn
//
//
LRESULTCALLBACKWndProc(HWNDhWnd,UINTmessage,WPARAMwParam,LPARAMlParam)
{
intwmId,wmEvent;
PAINTSTRUCTps;
HDChdc;
switch(message)
{
caseWM_COMMAND:
wmId=LOWORD(wParam);
wmEvent=HIWORD(wParam);
//Parsethemenuselections:
switch(wmId)
{
caseIDM_ABOUT:
DialogBox(hInst,MAKEINTRESOURCE(IDD_ABOUTBOX),hWnd,About);
break;
caseIDM_EXIT:
DestroyWindow(hWnd);
break;
default:
returnDefWindowProc(hWnd,message,wParam,lParam);
}
break;
caseWM_PAINT:
hdc=BeginPaint(hWnd,&ps);
//TODO:Addanydrawingcodehere...
EndPaint(hWnd,&ps);
break;
caseWM_DESTROY:
PostQuitMessage(0);
break;
default:
returnDefWindowProc(hWnd,message,wParam,lParam);
}
return0;
}
Atafirstlook,thisfunctionlooksconfusing,butitisrelativelysimpletounderstand.Assimplicitymattersintheseintroductorytutorials,thedefinitionofeachcasewillbe
separated.
WM_COMMAND
Thismessageissentwheneverauserinteractionoccurs,suchasmenuitemselection,orwhenaparentreceivesanotificationfromachildwindow.
caseWM_COMMAND:
wmId=LOWORD(wParam);
wmEvent=HIWORD(wParam);
//Parsethemenuselections:
switch(wmId)
{
caseIDM_ABOUT:
...
caseIDM_EXIT:
...
default:
returnDefWindowProc(hWnd,message,wParam,lParam);
}
break;
OneimportantthingtonotehereistheuseofmacrosLOWORD&HIWORD.
wmId=LOWORD(wParam);
wmEvent=HIWORD(wParam);
Beforeexplainingthemainpurposeofbothmacros,wemustcomprehendwhatwParamis.wParamisaparameteroftypeWPARAM.ThetypeWPARAMisanaliastoa32bits
unsignedinteger.Iftargetinga64bitsarchitecture,suchasWindowsx64,thiswillconstituteanaliastoa64bitsinteger,whichisequivalenttoanunsignedlonglong,or
unsignedlonglongint.
Assumingreadersarefamiliarwithbinaryrepresentation,LOWORD&HIWORDaremacrosforretrievingspecificbitsofwParam.Usingbitwiseoperators,theLOWORD
macrocanbeseenas:
#defineLOWORD(l)((WORD)(((DWORD_PTR)(l))&0xffff))
TheHIWORDmacroisdefinedas:
#defineHIWORD(l)((WORD)((((DWORD_PTR)(l))>>16)&0xffff))
Inshort,LOWORDsimplyperformslogicalconjunction(AND)operationwithvalue0xffffwhichclearstheupper16bits,leavingonlythelowerpartunaffected.
MarcAntoineLortie
HIWORD,itselfincludesoneextrabeforeLOWORD:tousetherightshiftoperators>>toshifttheupperparttotheright,thusoverridingthelower16bits,andthenapplying
(Currentlyunavailable)Freetips/help/codereview,seefieldsspecifiedbelow
logicalconjunctiontocleartheupperpart.
Follow
SIGNUP
https://www.codementor.io/malortie/buildwin32apiappwindowsmessagesccppvisualstudiodu107sbya 7/9
06/05/2017 BuildingaWin32App,Part2:WindowsandMessages|Codementor
Note:Wemustensuretocleartheupperpartagain,otherwiseitcouldresultinimpropervalues.
Onceretrieved,thisvaluewilltellusthemessageID,whereprefixessuchasIDMareusedasnamingconventionstoindicatethatthisrepresentsamessageID.Thisleadsus
toanotherconditionalbranchwithtwocases,IDM_ABOUTandIDM_EXIT.
caseWM_COMMAND:
wmId=LOWORD(wParam);
wmEvent=HIWORD(wParam);
//Parsethemenuselections:
switch(wmId)
{
caseIDM_ABOUT:
...
caseIDM_EXIT:
...
default:
returnDefWindowProc(hWnd,message,wParam,lParam);
}
break;
IDM_ABOUT
Whenusersclicktheclosebutton(X)atthetoprightcorner,thiscausesthewindowtosendamessageWM_COMMANDwithargumentIDM_ABOUTpassedtowParamasthe
lowword(orlowpart),whichisretrievedwithmacroLOWORD.IfthevaluecorrespondstoIDM_ABOUT,thenDialogBoxiscalledandinitializeadialogthatdisplays
informationabouttheauthorsoftheapplication.IwillnotexplainhowDialogBoxworksforsimplicitypurposes.Thiswillbecoveredinfurthertutorials.
caseIDM_ABOUT:
DialogBox(hInst,MAKEINTRESOURCE(IDD_ABOUTBOX),hWnd,About);
break;
IDM_EXIT
Whenusersclicktheclosebutton(X)atthetoprightcorner,thiscausesthewindowtosendamessageWM_COMMANDwithargumentIDM_EXITpassedtowParamasthe
lowword(orlowpart),whichisretrievedwithmacroLOWORD.IfthevaluecorrespondstoIDM_EXIT,thentheDestroyWindowfunctioniscalled,whichwillthensenda
WM_DESTROYmessagetothewindow,whichwewillseefurtherinthistutorial.
caseIDM_EXIT:
DestroyWindow(hWnd);
break;
WM_PAINT
TheWM_PAINTidentifierisusedtodescribethepaintevent.Thiseventoccurseverytimeawindowisredrawn.ThefunctionBeginPaintandEndPaintareusedtospecifyboth
startandendofdrawingprocess.Onreturn,allthedrawingthatwasdonewillbesenttoscreen.
caseWM_PAINT:
hdc=BeginPaint(hWnd,&ps);
//TODO:Addanydrawingcodehere...
EndPaint(hWnd,&ps);
break;
WM_DESTROY
ThiscommandiscalledwhenevertheDestroyWindowfunctioniscalled.Forexample,wheneverauserclickstheclosebuttonofthewindow,attheupperrightcorner
(windowsapplications),DestroyWindowiscalled.Bydoingso,amessageWM_DESTROYisthensenttothewindowhandle.
CallofPostQuitMessageisusedtoindicatethatthewindowisterminating,thuscausingthemessagelooptoend.
caseWM_DESTROY:
PostQuitMessage(0);
break;
Default
Inthedefaultcase,afunctionnamedDefWindowProcisusedasadefaultreturnresult.
default:
returnDefWindowProc(hWnd,message,wParam,lParam);
ThisfunctionsimplycallsthedefaultwindowproceduretoprocessallmessagesthatwerenotcaughtinWndProc.Bytheendofthisfunction,thisleadsusbacktothe
messageloop,whichwillcontinueprocessmessagesthatareinthemessagequeue,orwaituntilamessageisreceived.
Conclusion
Fromthere,readersshouldbefamiliarwiththebasicsofaWin32API.ReadersshouldhaveafairunderstandingfromaconceptualpointofviewofWin32'sevent&
messageprocessingandhowthemainloopisinteractingwiththese.Readersareencouragedtoreadthistutorialagaintoensurecorrectunderstanding,asfurthertutorials
willcoverandexpandconceptsviewedthroughoutthislecture.
MarcAntoineLortie
Part3:CreatingaWindowfromScratch
(Currentlyunavailable)Freetips/help/codereview,seefieldsspecifiedbelow
FollowPart4:ApplyingResourcestoaWindow
SIGNUP
https://www.codementor.io/malortie/buildwin32apiappwindowsmessagesccppvisualstudiodu107sbya 8/9
06/05/2017 BuildingaWin32App,Part2:WindowsandMessages|Codementor
C++Cvisualstudiowin32
Report
MarcAntoineLortie
(Currentlyunavailable)Freetips/help/codereview,seefieldsspecifiedbelow
Programminglanguages*56yearsexperiencewithC/C++programming.*23yearsexperiencewithC#programming.*12yearsofexperiencewithJava*12yearsof
experiencewithPythonAPI*45yearsofexperiencewith...
Follow
IanByrd
CompetitiveProgramming101:TheGood,TheGreat,&TheUgly
JonDavis
QuickIntrotoMSBuildProjects
DUSHYANTKUMAR
C++features:Userdefinedliterals
Leaveareply
submit
DiscoverandreadmorepostsfromMarcAntoineLortie
getstarted
Enjoythispost?
LeavealikeandcommentforMarcAntoine
https://www.codementor.io/malortie/buildwin32apiappwindowsmessagesccppvisualstudiodu107sbya 9/9