动态创建一个右键菜单,将可供选择的各项列出来。
每个菜单项添加一个ID,因为弹出菜单有几项是不确定的,所以不能逐一添加菜单响应函数,而是将命令都映射到
如下类型的函数中,UINT nID为添加菜单项是设置的ID。依据该ID来判断用户点击的是哪个菜单项。
void OnShowMember(UINT nID)
006 | #include "popMenuDlg.h" |
012 | <SPAN style= "BACKGROUND-COLOR: #ffff00" > |
013 | const int MENU_START = 1100; |
014 | const int MENU_END = 1200; |
015 | </SPAN>CpopMenuDlg::CpopMenuDlg(CWnd* pParent ) |
016 | : CDialog(CpopMenuDlg::IDD, pParent) |
018 | m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); |
021 | void CpopMenuDlg::DoDataExchange(CDataExchange* pDX) |
023 | CDialog::DoDataExchange(pDX); |
026 | BEGIN_MESSAGE_MAP(CpopMenuDlg, CDialog) |
030 | ON_BN_CLICKED(IDC_BUTTON1, &CpopMenuDlg::OnBnClickedButton1) |
031 | <SPAN style= "BACKGROUND-COLOR: #ffff00" > |
032 | ON_COMMAND_RANGE(MENU_START, MENU_END, &CpopMenuDlg::OnShowMember) |
033 | </SPAN>END_MESSAGE_MAP() |
036 | <SPAN style= "BACKGROUND-COLOR: #ffff00" > |
037 | void CpopMenuDlg::OnShowMember( UINT nID) |
039 | int nIndex = nID - MENU_START; |
040 | GetDlgItem(IDC_STATIC_MEMBER)->SetWindowText(m_MemberList[nIndex]); |
043 | BOOL CpopMenuDlg::OnInitDialog() |
045 | CDialog::OnInitDialog(); |
048 | m_MemberList.Add(_T( "宇智波Q" )); |
049 | m_MemberList.Add(_T( "宇智波左助" )); |
050 | m_MemberList.Add(_T( "宇智波斑" )); |
051 | m_MemberList.Add(_T( "宇智波柚" )); |
056 | void CpopMenuDlg::OnSysCommand( UINT nID, LPARAM lParam) |
058 | if ((nID & 0xFFF0) == IDM_ABOUTBOX) |
063 | CDialog::OnSysCommand(nID, lParam); |
071 | void CpopMenuDlg::OnPaint() |
077 | SendMessage(WM_ICONERASEBKGND, reinterpret_cast < WPARAM >(dc.GetSafeHdc()), 0); |
080 | int cxIcon = GetSystemMetrics(SM_CXICON); |
081 | int cyIcon = GetSystemMetrics(SM_CYICON); |
083 | GetClientRect(&rect); |
084 | int x = (rect.Width() - cxIcon + 1) / 2; |
085 | int y = (rect.Height() - cyIcon + 1) / 2; |
088 | dc.DrawIcon(x, y, m_hIcon); |
098 | HCURSOR CpopMenuDlg::OnQueryDragIcon() |
100 | return static_cast < HCURSOR >(m_hIcon); |
103 | void CpopMenuDlg::OnBnClickedButton1() |
105 | <SPAN style= "BACKGROUND-COLOR: #ffff00" > POINT pt; |
110 | popMenu.CreatePopupMenu(); |
112 | for ( int i = 0; i < m_MemberList.GetCount(); ++i) |
114 | popMenu.AppendMenu(MF_STRING, MENU_START + i, m_MemberList[i]); |
117 | popMenu.TrackPopupMenu(TPM_LEFTALIGN, pt.x, pt.y, this ); |
118 | popMenu.DestroyMenu(); |