菜单编程动态添加.docx
- 文档编号:13701944
- 上传时间:2023-06-16
- 格式:DOCX
- 页数:14
- 大小:20.08KB
菜单编程动态添加.docx
《菜单编程动态添加.docx》由会员分享,可在线阅读,更多相关《菜单编程动态添加.docx(14页珍藏版)》请在冰点文库上搜索。
菜单编程动态添加
此文章已于13:
58:
102011-3-31发布到luowei505050的专栏
菜单编程_动态添加
帐户luowei505050的专栏
类别程序设计
1.
动态的添加、删除、插入菜单新建一个MFC单文档应用程序,取名Menu2.
添加菜单,在CMainFrame:
:
OnCreate(LPCREATESTRUCTlpCreateStruct)中添加:
CMenumenu;
menu.CreatePopupMenu();//创建一个空的弹出菜单
GetMenu()->AppendMenu(MF_POPUP,(UINT)menu.m_hMenu,"NO_1");//添加一个弹出菜单
menu.Detach();
注释:
CreatePopupMenu
TheCreatePopupMenufunctioncreatesadrop-downmenu,submenu,orshortcutmenu.Themenuisinitiallyempty.YoucaninsertorappendmenuitemsbyusingtheInsertMenuItemfunction.YoucanalsousetheInsertMenufunctiontoinsertmenuitemsandtheAppendMenufunctiontoappendmenuitems.
HMENUCreatePopupMenu(VOID);
Parameters
Thisfunctionhasnoparameters.
ReturnValues
Ifthefunctionsucceeds,thereturnvalueisahandletothenewlycreatedmenu.
Ifthefunctionfails,thereturnvalueisNULL.Togetextendederrorinformation,callGetLastError.
Remarks
Theapplicationcanaddthenewmenutoanexistingmenu,oritcandisplayashortcutmenubycallingtheTrackPopupMenuExorTrackPopupMenufunctions.
Resourcesassociatedwithamenuthatisassignedtoawindowarefreedautomatically.Ifthemenuisnotassignedtoawindow,anapplicationmustfreesystemresourcesassociatedwiththemenubeforeclosing.AnapplicationfreesmenuresourcesbycallingtheDestroyMenufunction.
-----------------------------------------------------------------------------------------------
AppendMenu
TheAppendMenufunctionappendsanewitemtotheendofthespecifiedmenubar,drop-downmenu,submenu,orshortcutmenu.Youcanusethisfunctiontospecifythecontent,appearance,andbehaviorofthemenuitem.
Note TheAppendMenufunctionhasbeensupersededbytheInsertMenuItemfunction.YoucanstilluseAppendMenu,however,ifyoudonotneedanyoftheextendedfeaturesofInsertMenuItem.
BOOLAppendMenu(
HMENUhMenu,//handletomenu
UINTuFlags,//menu-itemoptions
UINT_PTRuIDNewItem,//identifier,menu,orsubmenu
LPCTSTRlpNewItem//menu-itemcontent
);
ReturnValues
Ifthefunctionsucceeds,thereturnvalueisnonzero.Ifthefunctionfails,thereturnvalueiszero.Togetextendederrorinformation,callGetLastError.
2.
插入菜单项,在CMainFrame:
:
OnCreate(LPCREATESTRUCTlpCreateStruct)中继续添加:
GetMenu()->InsertMenu(2,MF_BYPOSITION|MF_POPUP,(UINT)menu.m_hMenu,"NO_1");//插入菜单
menu.AppendMenu(MF_STRING,111,"Hello");//添加菜单项
menu.AppendMenu(MF_STRING,112,"Good");
menu.AppendMenu(MF_STRING,113,"Nice");
menu.Detach();//分离与controlbar的连接
GetMenu()->GetSubMenu(0)->AppendMenu(MF_STRING,114,"Welcome");//在第1个弹出菜单添加项
GetMenu()->GetSubMenu(0)->InsertMenu(ID_FILE_OPEN,MF_BYCOMMAND|MF_STRING,115,"GoodLuck");//插入菜单项
注释:
InsertMenu
TheInsertMenufunctioninsertsanewmenuitemintoamenu,movingotheritemsdownthemenu.
Note TheInsertMenufunctionhasbeensupersededbytheInsertMenuItemfunction.YoucanstilluseInsertMenu,however,ifyoudonotneedanyoftheextendedfeaturesofInsertMenuItem.
BOOLInsertMenu(
HMENUhMenu,//handletomenu
UINTuPosition,//itemthatnewitemprecedes
UINTuFlags,//options
UINT_PTRuIDNewItem,//identifier,menu,orsubmenu
LPCTSTRlpNewItem//menuitemcontent
);
ReturnValues
Ifthefunctionsucceeds,thereturnvalueisnonzero.
Ifthefunctionfails,thereturnvalueiszero.Togetextendederrorinformation,callGetLastError.
删除菜单,在CMainFrame:
:
OnCreate(LPCREATESTRUCTlpCreateStruct)中继续添加:
GetMenu()->DeleteMenu(1,MF_BYPOSITION);//删除编辑菜单
GetMenu()->GetSubMenu(0)->DeleteMenu(2,MF_BYPOSITION);//删除打开菜单
注释:
DeleteMenu
TheDeleteMenufunctiondeletesanitemfromthespecifiedmenu.Ifthemenuitemopensamenuorsubmenu,thisfunctiondestroysthehandletothemenuorsubmenuandfreesthememoryusedbythemenuorsubmenu.
BOOLDeleteMenu(
HMENUhMenu,//handletomenu
UINTuPosition,//menuitemidentifierorposition
UINTuFlags//option
);
ReturnValues
Ifthefunctionsucceeds,thereturnvalueisnonzero.
Ifthefunctionfails,thereturnvalueiszero.Togetextendederrorinformation,callGetLastError.
Remarks
TheapplicationmustcalltheDrawMenuBarfunctionwheneveramenuchanges,whetherornotthemenuisinadisplayedwindow.
增加菜单项的命令响应,在Resource.h中添加:
#defineIDM_HELLO111
将CMainFrame:
:
OnCreate(LPCREATESTRUCTlpCreateStruct)修改:
menu.AppendMenu(MF_STRING,IDM_HELLO,"Hello");//添加菜单项
在MainFrm.h文件中添加消息原型:
protected:
//{{AFX_MSG(CMainFrame)
afx_msgintOnCreate(LPCREATESTRUCTlpCreateStruct);
//NOTE-theClassWizardwilladdandremovememberfunctionshere.
//DONOTEDITwhatyouseeintheseblocksofgeneratedcode!
//}}AFX_MSG
afx_msgvoidOnHello();
DECLARE_MESSAGE_MAP()
在MainFrm.cpp文件中添加消息映射:
BEGIN_MESSAGE_MAP(CMainFrame,CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
//NOTE-theClassWizardwilladdandremovemappingmacroshere.
//DONOTEDITwhatyouseeintheseblocksofgeneratedcode!
ON_WM_CREATE()
//}}AFX_MSG_MAP
ON_COMMAND(IDM_HELLO,OnHello)
END_MESSAGE_MAP()
并添加一个函数:
voidCMainFrame:
:
OnHello()
{
MessageBox("Hello!
");
}
编写一个电话本程序:
在CMenu2View类中添加一个WM_CHAR消息,添加成员变量:
public:
CStringArraym_strArray;
private:
CMenum_menu;
intm_nIndex;
CStringm_strLine;
在CMenu2View:
:
CMenu2View()函数中赋初值:
m_nIndex=-1;
m_strLine="";
在CMenu2View中添加WM_CHAR消息响应函数,并写上以下代码:
voidCMenu2View:
:
OnChar(UINTnChar,UINTnRepCnt,UINTnFlags)
{
//TODO:
Addyourmessagehandlercodehereand/orcalldefault
CClientDCdc(this);
if(0x0d==nChar)
{
if(0==++m_nIndex)
{
m_menu.CreateMenu();
GetParent()->GetMenu()->AppendMenu(MF_POPUP,(UINT)m_menu.m_hMenu,"PhoneBook");//获取菜单项
GetParent()->DrawMenuBar();//重画改变的菜单栏
}
m_menu.AppendMenu(MF_STRING,IDM_PHONE1+m_nIndex,m_strLine.Left(m_strLine.Find('')));
m_strArray.Add(m_strLine);//将增加的一个字符保存到字符数组中
m_strLine.Empty();//清空先前的字符
Invalidate();//擦除先前窗口的内容,缺省为TRUE
}
else
{
m_strLine+=nChar;
dc.TextOut(0,0,m_strLine);//输出字符串
}
CView:
:
OnChar(nChar,nRepCnt,nFlags);
}
注释:
CStringArray
TheCStringArrayclasssupportsarraysofCStringobjects.
ThememberfunctionsofCStringArrayaresimilartothememberfunctionsofclassCObArray.Becauseofthissimilarity,youcanusetheCObArrayreferencedocumentationformemberfunctionspecifics.WhereveryouseeaCObjectpointerasareturnvalue,substituteaCString(notaCStringpointer).WhereveryouseeaCObjectpointerasafunctionparameter,substituteaLPCTSTR.
CObject*CObArray:
:
GetAt(int
forexample,translatesto
CStringCStringArray:
:
GetAt(int
and
voidSetAt(int
translatesto
voidSetAt(int
CStringArrayincorporatestheIMPLEMENT_SERIALmacrotosupportserializationanddumpingofitselements.IfanarrayofCStringobjectsisstoredtoanarchive,eitherwithanoverloadedinsertionoperatororwiththeSerializememberfunction,eachelementisserializedinturn.
Note Beforeusinganarray,useSetSizetoestablishitssizeandallocatememoryforit.IfyoudonotuseSetSize,addingelementstoyourarraycausesittobefrequentlyreallocatedandcopied.Frequentreallocationandcopyingareinefficientandcanfragmentmemory.
Ifyouneedadumpofindividualstringelementsinthearray,youmustsetthedepthofthedumpcontextto1orgreater.
WhenaCStringarrayisdeleted,orwhenitselementsareremoved,stringmemoryisfreedasappropriate.
FormoreinformationonusingCStringArray,seethearticleCollectionsinVisualC++Programmer’sGuide.
#include
-------------------------------------------------------------------------------------------------
CObArray:
:
Add
intAdd(CObject*newElement);
throw(CMemoryException);
ReturnValue
Theindexoftheaddedelement.
Parameters
newElement
TheCObjectpointertobeaddedtothisarray.
Remarks
Addsanewelementtotheendofanarray,growingthearrayby1.IfSetSizehasbeenusedwithannGrowByvaluegreaterthan1,thenextramemorymaybeallocated.However,theupperboundwillincreasebyonly1.
ThefollowingtableshowsothermemberfunctionsthataresimilartoCObArray:
:
Add.
-----------------------------------------------------------------------------------------------------------------
CWindow:
:
Invalidate
BOOLInvalidate(BOOLbErase=TRUE);
SeeInvalidateRectintheWin32SDK.
Remarks
Invalidatestheentireclientarea.PassesNULLfortheRECTparametertotheInvalidateRectWin32function.
Example
//ThefollowingexampleattachesanHWNDtotheCWindowobjectand
//callsCWindow:
:
Invalidate()toinvalidatetheentireclientarea
CWindowmyWindow;
myWindow.Attach(hWndFoo);
myWindow.Invalidate();
并相继添加五个按钮:
protected:
//{{AFX_MSG(CMenu2View)
afx_msgvoidOnChar(UINTnChar,UINTnRepCnt,UINTnFlags);
//}}AFX_MSG
afx_msgvoidOnPhone1();//消息原型声明
afx_msgvoidOnPhone2();
afx_msgvoidOnPhone3();
afx_msgvoidOnPhone4();
afx_msgvoidOnPhone5();
DECLARE_MESSAGE_MAP()
-----------------------------------------------------
BEGIN_MESSAGE_MAP(CMenu2View,CView)
//{{AFX_MSG_MAP(CMenu2View)
ON_WM_CHAR()
//}}AFX_MSG_MAP
//Standardprintingcommands
ON_COMMAND(IDM_PHONE1,OnPhone1)//消息映射
ON_COMMAND(IDM_PHONE2,OnPhone2)
ON_COMMAND(IDM_PHONE3,OnPhone3)
ON_COMMAND(IDM_PHONE4,OnPhone4)
ON_COMMAND(IDM_PHONE5,OnPhone5)
ON_COMMAND(ID_FILE_PRINT,CView:
:
OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT,CView:
:
OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW,CView:
:
OnFilePrintPreview)
END_MESSAGE_MAP()
-------------------------------------------------------------------------------------------------------------
voidCMenu2View:
:
OnPhone1()//消息响应函数
{
//TODO:
Addyourcommandhandlercodehere
CClientDCdc(this);
dc.TextOut(0,0,
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 菜单 编程 动态 添加