菜单编程_动态添加

来源:互联网 发布:天刀男捏脸数据白玉京 编辑:程序博客网 时间:2024/06/05 22:39

1.

动态的添加、删除、插入菜单新建一个MFC单文档应用程序,取名Menu2.

添加菜单,在CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)中添加:

CMenu menu;

menu.CreatePopupMenu();//创建一个空的弹出菜单

GetMenu()->AppendMenu(MF_POPUP,(UINT)menu.m_hMenu,"NO_1");//添加一个弹出菜单

menu.Detach();

注释:

CreatePopupMenu

The CreatePopupMenu function creates a drop-down menu, submenu, or shortcut menu. The menu is initially empty. You can insert or append menu items by using the InsertMenuItem function. You can also use the InsertMenu function to insert menu items and the AppendMenu function to append menu items.

HMENU CreatePopupMenu(VOID);

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is a handle to the newly created menu.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The application can add the new menu to an existing menu, or it can display a shortcut menu by calling the TrackPopupMenuEx or TrackPopupMenu functions.

Resources associated with a menu that is assigned to a window are freed automatically. If the menu is not assigned to a window, an application must free system resources associated with the menu before closing. An application frees menu resources by calling the DestroyMenu function.

 

-----------------------------------------------------------------------------------------------

AppendMenu

The AppendMenu function appends a new item to the end of the specified menu bar, drop-down menu, submenu, or shortcut menu. You can use this function to specify the content, appearance, and behavior of the menu item.

Note  The AppendMenu function has been superseded by the InsertMenuItem function. You can still use AppendMenu, however, if you do not need any of the extended features of InsertMenuItem.

BOOL AppendMenu(

HMENUhMenu, // handle to menu

UINTuFlags, // menu-item options

UINT_PTRuIDNewItem, // identifier, menu, or submenu

LPCTSTRlpNewItem// menu-item content

);

Return Values

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

2.

插入菜单项,在CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)中继续添加:

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();//分离与control bar的连接

GetMenu()->GetSubMenu(0)->AppendMenu(MF_STRING,114,"Welcome");//在第1个弹出菜单添加项

GetMenu()->GetSubMenu(0)->InsertMenu(ID_FILE_OPEN,MF_BYCOMMAND|MF_STRING,115,"GoodLuck");//插入菜单项

注释:

InsertMenu

The InsertMenu function inserts a new menu item into a menu, moving other items down the menu.

Note  The InsertMenu function has been superseded by the InsertMenuItem function. You can still use InsertMenu, however, if you do not need any of the extended features of InsertMenuItem.

BOOL InsertMenu(

HMENUhMenu, // handle to menu

UINTuPosition, // item that new item precedes

UINTuFlags, // options

UINT_PTRuIDNewItem, // identifier, menu, or submenu

LPCTSTRlpNewItem// menu item content

);

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

删除菜单,在CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)中继续添加:

GetMenu()->DeleteMenu(1,MF_BYPOSITION);//删除编辑菜单

GetMenu()->GetSubMenu(0)->DeleteMenu(2,MF_BYPOSITION);//删除打开菜单

注释:

DeleteMenu

The DeleteMenu function deletes an item from the specified menu. If the menu item opens a menu or submenu, this function destroys the handle to the menu or submenu and frees the memory used by the menu or submenu.

BOOL DeleteMenu(

HMENUhMenu, // handle to menu

UINTuPosition, // menu item identifier or position

UINTuFlags// option

);

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The application must call the DrawMenuBar function whenever a menu changes, whether or not the menu is in a displayed window.

增加菜单项的命令响应,在Resource.h中添加:

#define IDM_HELLO                    111

将CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)修改:

menu.AppendMenu(MF_STRING,IDM_HELLO,"Hello");//添加菜单项

在MainFrm.h文件中添加消息原型:

protected:

    //{{AFX_MSG(CMainFrame)

    afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);

        // NOTE - the ClassWizard will add and remove member functions here.

        // DO NOT EDIT what you see in these blocks of generated code!

    //}}AFX_MSG

    afx_msg void OnHello();

    DECLARE_MESSAGE_MAP()

在MainFrm.cpp文件中添加消息映射:

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)

    //{{AFX_MSG_MAP(CMainFrame)

        // NOTE - the ClassWizard will add and remove mapping macros here.

        // DO NOT EDIT what you see in these blocks of generated code !

    ON_WM_CREATE()

    //}}AFX_MSG_MAP

    ON_COMMAND(IDM_HELLO,OnHello)

END_MESSAGE_MAP()

并添加一个函数:

void CMainFrame::OnHello()

{

    MessageBox("Hello!");

}

 

编写一个电话本程序:

在CMenu2View类中添加一个WM_CHAR消息,添加成员变量:

public:

    CStringArray m_strArray;

private:

    CMenu m_menu;

    int m_nIndex;

CString m_strLine;

在CMenu2View::CMenu2View()函数中赋初值:

m_nIndex=-1;

m_strLine="";

在CMenu2View中添加WM_CHAR消息响应函数,并写上以下代码:

void CMenu2View::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)

{

    // TODO: Add your message handler code here and/or call default

    CClientDC dc(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

The CStringArray class supports arrays of CString objects.

The member functions of CStringArray are similar to the member functions of class CObArray. Because of this similarity, you can use the CObArray reference documentation for member function specifics. Wherever you see a CObject pointer as a return value, substitute a CString (not a CString pointer). Wherever you see a CObject pointer as a function parameter, substitute a LPCTSTR.

CObject* CObArray::GetAt( int ) const;

for example, translates to

CString CStringArray::GetAt( int ) const;

and

void SetAt( int , CObject* )

translates to

void SetAt( int , LPCTSTR )

CStringArray incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. If an array of CString objects is stored to an archive, either with an overloaded insertion operator or with the Serialize member function, each element is serialized in turn.

Note   Before using an array, use SetSize to establish its size and allocate memory for it. If you do not use SetSize, adding elements to your array causes it to be frequently reallocated and copied. Frequent reallocation and copying are inefficient and can fragment memory.

If you need a dump of individual string elements in the array, you must set the depth of the dump context to 1 or greater.

When a CString array is deleted, or when its elements are removed, string memory is freed as appropriate.

For more information on using CStringArray, see the article Collections in Visual C++ Programmer's Guide.

#include

-------------------------------------------------------------------------------------------------

CObArray::Add

intAdd(CObject*newElement);
throw(CMemoryException);

Return Value

The index of the added element.

Parameters

newElement

The CObject pointer to be added to this array.

Remarks

Adds a new element to the end of an array, growing the array by 1. If SetSize has been used with an nGrowBy value greater than 1, then extra memory may be allocated. However, the upper bound will increase by only 1.

The following table shows other member functions that are similar to CObArray::Add.

-----------------------------------------------------------------------------------------------------------------

CWindow::Invalidate

BOOLInvalidate(BOOLbErase=TRUE);

See InvalidateRect in the Win32 SDK.

Remarks

Invalidates the entire client area. Passes NULL for the RECT parameter to the InvalidateRect Win32 function.

Example

//The following example attaches an HWND to the CWindow object and

//calls CWindow::Invalidate() to invalidate the entire client area

 

CWindow myWindow;

myWindow.Attach(hWndFoo);

myWindow.Invalidate();

 

并相继添加五个按钮:

protected:

    //{{AFX_MSG(CMenu2View)

    afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);

    //}}AFX_MSG

    afx_msg void OnPhone1();//消息原型声明

    afx_msg void OnPhone2();

    afx_msg void OnPhone3();

    afx_msg void OnPhone4();

    afx_msg void OnPhone5();

    DECLARE_MESSAGE_MAP()

-----------------------------------------------------

BEGIN_MESSAGE_MAP(CMenu2View, CView)

    //{{AFX_MSG_MAP(CMenu2View)

    ON_WM_CHAR()

    //}}AFX_MSG_MAP

    // Standard printing commands

    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()

-------------------------------------------------------------------------------------------------------------

void CMenu2View::OnPhone1() //消息响应函数

{

    // TODO: Add your command handler code here

    CClientDC dc(this);

    dc.TextOut(0,0,m_strArray.GetAt(0));

}

 

void CMenu2View::OnPhone2()//消息响应函数

{

    // TODO: Add your command handler code here

    CClientDC dc(this);

    dc.TextOut(0,0,m_strArray.GetAt(1));

}

 

void CMenu2View::OnPhone3()//消息响应函数

{

    // TODO: Add your command handler code here

    CClientDC dc(this);

    dc.TextOut(0,0,m_strArray.GetAt(2));

}

 

void CMenu2View::OnPhone4()//消息响应函数

{

    // TODO: Add your command handler code here

    CClientDC dc(this);

    dc.TextOut(0,0,m_strArray.GetAt(3));

}

 

void CMenu2View::OnPhone5()//消息响应函数

{

    // TODO: Add your command handler code here

    CClientDC dc(this);

    dc.TextOut(0,0,m_strArray.GetAt(4));

}

用框架类来捕获消息,在CMainFrame类中,添加一个OnCommand虚函数,并添加:

BOOL CMainFrame::OnCommand(WPARAM wParam, LPARAM lParam)

{

    // TODO: Add your specialized code here and/or call the base class

    int MenuCmdId=LOWORD(wParam);//获得wParam的低两个字节

    CMenu2View *pView=(CMenu2View*)GetActiveView();//得到CMenu2View的一个指针

    if(MenuCmdId>=IDM_PHONE1 && MenuCmdIdm_strArray.GetSize()/*获得这个变量的大小*/)

    {

        CClientDC dc(pView);//用指向View类的指针

        dc.TextOut(0,0,pView->m_strArray.GetAt(MenuCmdId-IDM_PHONE1));//输出

        //MessageBox("Test");

        return TRUE;

    }

    return CFrameWnd::OnCommand(wParam, lParam);

}

注释:

CWnd::OnCommand

This method is called by the framework when the user selects an item from a menu, when a child control sends a notification message, or when an accelerator keystroke is translated.

virtual BOOL OnCommand( 

WPARAM wParam, 

LPARAM lParam);

Parameters

wParam

The low-order word of wParam identifies the command ID of the menu item, control, or accelerator. The high-order word of wParam specifies the notification message if the message is from a control. If the message is from an accelerator, the high-order word is 1. If the message is from a menu, the high-order word is 0.

lParam

Identifies the control that sends the message if the message is from a control. Otherwise, lParam is 0.

Return Value

An application returns nonzero if it processes this message; otherwise, it is zero.

Remarks

OnCommand processes the message map for control notification and ON_COMMAND entries, and calls the appropriate method.

Override this method in your derived class to handle the WM_COMMAND message. An override will not process the message map unless the base class OnCommand is called.

This method is called by the framework to allow your application to handle a Windows CE message. The parameters passed to your method reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this method, that implementation will use the parameters originally passed with the message and not the parameters you supply to the method.

-------------------------------------------------------------------------------------------------------

LOWORD

The LOWORD macro retrieves the low-order word from the specified value.

WORD LOWORD(

  DWORDdwValue

);

Parameters

dwValue

Specifies the value to be converted.

Return Values

The return value is the low-order word of the specified value.

---------------------------------------------------------------------------------------------------------------

CFrameWnd::GetActiveView

This method obtains a pointer to the active view, if any, attached to a frame window, CFrameWnd.

CView* GetActiveView( ) 

const;

Return Value

Specifies a pointer to the current CView. If there is no current view, returns NULL.

----------------------------------------------------------------------------------------------------------------

注:要在MainFrm.cpp中添加一个头文件Menu2View.h ,并在Menu2View..h中添加一个头文件#include "menu2Doc.h" 。OK ^_^ !!!

原创粉丝点击