How to handle pop-up menu event?

Hi I use VC++ MFC 4.2 Professional.

I need to handle a pop-up menu on a CListCtrl item. 

So when users right click on one of the item, a pop-up menu will be shown. 

I have successfully creating the pop-up menu. 

Now the problem is how to handle those menu if users choose one of them?

I mean how to catch the event?

Thank you very much.

void CToiawaseDlg::OnRclickLstData(NMHDR* pNMHDR, LRESULT* pResult) 
{
	int iIndex = m_lst_data.GetNextItem( -1, LVNI_SELECTED );
	if( iIndex != -1 ){
		CHistory* pHistory = ( CHistory* )m_lst_data.GetItemData( iIndex );
		ASSERT( pHistory );
		HMENU hMnu = ::CreatePopupMenu();
		AppendMenu( hMnu, MF_STRING, NULL, "Update" );
		AppendMenu( hMnu, MF_STRING, NULL, "Delete" );

		POINT point;
		GetCursorPos( &point );
		
		::TrackPopupMenu( hMnu,TPM_LEFTBUTTON | TPM_RIGHTBUTTON, point.x, point.y, 
NULL, this->m_hWnd, NULL );
           }
           
            *pResult = 0;

}
0
landon (165)
8/25/2008 4:30:01 AM
vc.mfc 33608 articles. 0 followers. Follow

3 Replies
418 Views

Similar Articles

[PageSpeed] 48

See below...
On Sun, 24 Aug 2008 21:30:01 -0700, Landon <Landon@discussions.microsoft.com> wrote:

>Hi I use VC++ MFC 4.2 Professional.
>
>I need to handle a pop-up menu on a CListCtrl item. 
>
>So when users right click on one of the item, a pop-up menu will be shown. 
>
>I have successfully creating the pop-up menu. 
>
>Now the problem is how to handle those menu if users choose one of them?
>
>I mean how to catch the event?
>
>Thank you very much.
>
>void CToiawaseDlg::OnRclickLstData(NMHDR* pNMHDR, LRESULT* pResult) 
>{
>	int iIndex = m_lst_data.GetNextItem( -1, LVNI_SELECTED );
>	if( iIndex != -1 ){
>		CHistory* pHistory = ( CHistory* )m_lst_data.GetItemData( iIndex );
>		ASSERT( pHistory );
>		HMENU hMnu = ::CreatePopupMenu();
>		AppendMenu( hMnu, MF_STRING, NULL, "Update" );
>		AppendMenu( hMnu, MF_STRING, NULL, "Delete" );
****
You are MUCH better off creating a menu in the resource editor.  You would do
		CMenu menu;
		menu.LoadMenu(IDR_LISTCTRL_POPUP);
		CMenu * submenu = menu.GetSubmenu(0);
The problem is you have done something Very Bad: you have put an English-language constant
string (and an 8-bit string, at that!) in source code, which means it can't be localized.
Note that even VS4.2 supported Unicode, so literals should have _T() around them.

I'm not sure, but I think 4.2 had GetItemDataPtr, which is what you should use instead of
GetItemData.

And while you have ASSERT(pHistory) you haven;t actually written code to recover from the
situation if the value *is* NULL.

But note that ::AppendMenu takes the arguments
		HMENU menu
		UINT flags
		UINT id
		LPCTSTR name
you have created two menu items with the same ID, 0, so you cannot distinguish which menu
item was selected.  You would have to assign menu IDs to these (trivial if you don't try
to do it in code, by the way, since you would assign them in the menu editor), and you
would use those IDs as the third parameter.

Then you have to hand-edit the handlers into the message map, OUTSIDE the magical
AFX-comments that appear inside the message map (before or after doesn't make any
difference.  
	ON_COMMAND(ID_MY_UPDATE, OnMyUpdate)
	ON_COMMAND(ID_MY_DELETE, OnMyDelete)

void CMyClass::OnMyUpdate()
   {
    ... handle update here
   }

void CMyClass::OnMyDelete()
  {
   ... handle delete here
  }

Note that you have to figure out how to pass the information about which item to update or
delete across the boundary, either by using a member variable of the class or by setting
some state information in the control somehow (I suggest the member variable)
	
If you create the menu in the menu editor, you don't need to do the hand-editing, you can
add the command handler for the menu ID using the ClassWizard.			
*****
>
>		POINT point;
>		GetCursorPos( &point );
>		
>		::TrackPopupMenu( hMnu,TPM_LEFTBUTTON | TPM_RIGHTBUTTON, point.x, point.y, 
>NULL, this->m_hWnd, NULL );
****
                                submenu->TrackPopupMenu(TPM_...etc, this);
Now you have to add handlers as described above.

I find the mix of MFC and raw API a little strange, to say the least.  And I do NOT see
where you delete the menu, so you are going to leak resources like crazy.  In the scheme I
show, by using a CMenu local variable, the menu will be automatically freed when the
variable leaves scope.
			joe

****
>           }
>           
>            *pResult = 0;
>
>}
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15974)
8/25/2008 5:07:45 AM
Joe, thank you very much for your explanation. But I'm a bit don't understand.

The point I don't understand is how to link the menu and  the event handler. 
Like your explanation which said ON_COMMAND( ID_MY_UPDATE, OnMyUpdate );

I understand how to code the event handler but on the CMenu side I don't 
understand. 

I mean, how can C++ know that users chose the Update or the Delete and then 
do something on one of  those event handlers.

Can you please give me just one example using my code?

Thank you.
0
landon (165)
8/25/2008 6:32:02 AM
"Landon" <Landon@discussions.microsoft.com> wrote in message 
news:4E8EB56F-8D9D-4BEC-A8B5-1E6DF7C71144@microsoft.com...
> Joe, thank you very much for your explanation. But I'm a bit don't 
> understand.
>
> The point I don't understand is how to link the menu and  the event 
> handler.
> Like your explanation which said ON_COMMAND( ID_MY_UPDATE, OnMyUpdate );
>
> I understand how to code the event handler but on the CMenu side I don't
> understand.
>
> I mean, how can C++ know that users chose the Update or the Delete and 
> then
> do something on one of  those event handlers.


Each menu item must have an ID, which is a unique integer constant you 
assign.  Such as ID_MY_UPDATE, which would be defined in the resource.h 
file.  In your calls to AppendMenu you failed to pass an ID.

Look in resource.h and add some IDs in a range not being used by the 
automatic resource editor:
// resource.h
#define ID_MY_UPDATE    400
#define ID_MY_DELETE     401
// cpp
AppendMenu( hMnu, MF_STRING, ID_MY_UPDATE, "Update" );
AppendMenu( hMnu, MF_STRING, ID_MY_DELETE, "Delete" );

When the user selects a menu item that item's ID is passed with a message. 
Then the MFC message map looks up the message handler function that 
corresponds to the ID and calls it.

-- 
Scott McPhillips [VC++ MVP] 

0
Scott
8/25/2008 3:06:58 PM
Reply:

Similar Artilces:

pop up box
Hi, I want a pop up box to appear when the spreadsheet is opened. Is this possible? Also i would like the information in the pop up box to up issue - the box would have a number i.e. 3 and if this number is entered then it up issues to 4 in the pop up box so the next user knows that the number to take is 4. is this a crazy thing to ask? thanks Hi, You can create 1) a form and 2) an Workbook open event in VBA. something like: Userform1.show as to the number, I assume the numbers are on the worksheet, a textbox or label etc can be written to read the numbers ...

Exchange 2K to 2K3 migration
I'd like to get some advice on the best approach to handle the STM file during an Inter-Org mailbox move. The Exchange migration wizard will handle the the mailbox but how do you handle the content in the STM file? Thanks. You don't need to worry about it. Mailbox data is stored in both the EDB and STM files. Typically, message content from the Internet will be in the STM file. I'd suspect that when you migrate the mailboxes, all data will be converted to native MAPI format (moved to EDB file) and will then be moved to the new mailbox. -- Ben Winzenz Exchange MVP Me...

the menu bar is hidden under the title bar in a frame window generated from a dll ...
Hi, A very simple frame window generated from a dll of mine always has its menu bar hidden under the title bar. I have to click on the title bar to make the menu items show up. The following code that generates the frame window is actually copied from a small test program to the dll. In the test program, the code works just fine. So what makes the difference? I suspect IDR_MENU_TEST is only partially successfully loaded in the dll. Any reason for it? Pleave provide me any clue and hint. Your help is much appreciated. (I am using VS 2005) C2DGraphDoc *pDoc = new C2DGraphDoc...

Handle to an ActiveX control
Hi... What if I use GetModuleHandle(L"abc.ocx") in the InitInstance() of the of the App class derived from 'COleControlModule'...of the ActiveX control "abc.ocx" ? Will I get the Handle or it will return NULL....? I have encountered controls, in some of them..handle is found and in others its NULL... Wat is the reason behind this behavior..? Can any one explain? "Abby++" <asthana.abhinav@gmail.com> wrote in message news:1174308443.062622.51500@b75g2000hsg.googlegroups.com... > What if I use GetModuleHandle(L"abc.ocx") in the InitI...

invalid handle
hi frds i m very new in vc++ and i m founding too much difficulty in this so plz can any one solve this problem .... actully i m inserting a image in list box using this code ........ everything is returning write thing still it is saying invalid handle after ImageList_Add(hList,m_hBmpNew,0); when i m going to dibug it plz help me BOOL Fun() { // Create 256 color image lists HIMAGELIST hList = ImageList_Create(32,32, ILC_COLOR8 , 8, 1); HBITMAP m_hBmpNew = (HBITMAP) LoadImage( AfxGetInstanceHandle(), // handle to instance "c:\\img.bmp", /...

POP problem
I receive a number of daily and monthly html newsletters through my yahoo.co.uk account and use Yahoo's own POP service to import them to Outlook 2000. This works well, apart from one particular letter where occasionally the words of the text will run into one. For example 'wehavechoicesinhowwelookatproblems'. This happens every 2 or 3 days, and only affects a few sentences. Viewing the source code, it does appear that the problem is there i.e. that is the way the words appear in the html. But when I contacted the webmaster of the organization concerned, it was checked out,and I w...

Thunking a 32-bit HANDLE to a 64-bit HANDLE
Currently I am converting a 32-bit WDM driver to a 64-bit KMDF driver that will continue to work with our 32-bit DLL and our customer's 32-bit applications. The sample code for thunking 32-bit items shows the following Buffer->Handle = (HANDLE)Buffer32->Handle; see: http://msdn.microsoft.com/en-us/library/aa489604.aspx Buffer32->Handle is declared as UINT32 Handle The driver compiler issues error number C4312 for this cast. The code that I have adopted (to get it to compile) is: handlerInputs.hEvent = (HANDLE) (ULONG_PTR) p_handlerInputs3...

adding the freeze pane command to menu
Is it possible to add the Freeze Pane command to the menu that appears when you right click in a cell? thanks. One way: Type ALT-F11 to enter the VBE. Choose View/Immediate Window. In the Immediate Window, type or paste Application.CommandBars("Cell").Controls.Add Id:=443 followed by Enter. Note: At least in XL04, the control will toggle freezing panes, but the caption won't automatically change to "Unfreeze Panes" as it does in the Window menu. In article <31ae01c48f11$dc011150$a501280a@phx.gbl>, "MDC" <anonymous@discussions.microso...

Pop-ups
How do I delete the Popup " Work Offline" ? I never work money on line and this box keeps popping up whenever.If anyne knows please e-mail me.Thanks Perhaps you should read http://www.bollar.org/msmoney/#Q15. "Susan Scott" <sage783211@aol.com> wrote in message news:04f801c38c4a$4dabf750$a401280a@phx.gbl... > How do I delete the Popup " Work Offline" ? I never work > money on line and this box keeps popping up whenever.If > anyne knows please e-mail me.Thanks ...

Daily Bank Sweep
New GP Client that is reconciling for the first time their operating account. We have entered the last reconciled balance and dates as of 12/31/08. Operating account gets swept every night and redeposited the next day. With each sweep interest is calculated. My question is how to handle the last sweep of the month, which is a sweep in transit. We have tried entering as a decrease adjustment (not posting to GL as it should not effect the GL balance). We have also tried entering as an adjustment to see what the effect is. We don't even come close to the bank ending balance. Pl...

Handling blank data points
I have a chart which is has "" in a formula to clear contents when not applicable to show error. This results in the chart treating the cell as 0 and therefore ugly result in data point. All other post responses to this type of question suggest using NA() and conditional formation to hide the error.. Unfortunately when this is used this screws up my SUM() and AVG() formulas.. Any other suggestions? Thanks Jo Hi Jo, I don't know if this is the best way but what I have done under similar circumstances is use the #N/A for the chart series data column and then I use a hel...

Is It Possible to Control Access Warning Pop-Up Message Boxes?
When running an update query, Access displays a warning message box and prompts for a response ("You are about to run an update query that will modify data in your table"). I have a macro that runs a series of update queries. Right now, I get the message box/response for each query. In this case, there is no need for the message box at all. Is there a way to (ideally) turn off this message for the duration of the query) or to answer it once for all of the queries? Thanks TerryoMSN It is possible to turn the warning off ... WARNING!!! If you forget to turn it bac...

HANDLES
Hi All, how can I get info concerning the number of handles opened ? Thanks in advance Paolo You can have some information about the handles used by an application using 'Application Verifier' http://msdn.microsoft.com/en-us/library/aa446904.aspx -- Luca Calligaris (MVP-Windows Embedded) lucaDOTcalligarisATeurotechDOTcom www.eurotech.com "Paolo Cremonese" <cremonese@teledata-i.com> ha scritto nel messaggio news:O6rJxu5FLHA.2276@TK2MSFTNGP06.phx.gbl... > Hi All, > > how can I get info concerning the number of handles opened ?...

Handle Dialog Box From GP using Continuum API
Dear All I am working with VS2005, C#, Developer tool kit, GP 10. I am trying to use Continuum API to handle the response of Dialog Box because I can't do that using Developer tool kit. So I did create a new application "Microsoft Dynamics GP Add-in" C# I have this error: "Specified cast is not valid" I build my solution and I add the DLL in this path: C:\Program Files\Microsoft Dynamics\GP\AddIns Please I need your advise please. And I wrote the below Code using System; using System.Collections.Generic; using System.Text; using Microsoft.Dexterity.Bridge; usi...

Creating a Commandbar Menu
I have a form that I would like to creat a menu for the user. I would also like to create a menu for the application, sub menus, and shortcut menus. This would be the first time I've created a Commandbar Menu. Any good examples of how to do this would be appreciated. Thank you in advance. http://www.jamiessoftware.tk/articles/menubars.html That should get you started. -- Jack Leach www.tristatemachine.com "I haven''t failed, I''ve found ten thousand ways that don''t work." -Thomas Edison (1847-1931) "PosseJohn...

Slow in handling mailboxes
Outlook 2000 on Windows 2000, at latest levels. I have nine email services defined. Only four of these are set to be checked by Send/Receive; the others are occasional use and are unchecked in the Options/Mail Service list. Outlook is set to check my mailboxes only when I specifically request, not automatically. This a part of my junk-mail prevention strategy. I use MailWasherPro to interact directly with my ISP mailboxes, before the mail ever gets to Outlook Works great! As I added these occasional services, even through Outlook is set not to check them, I found that Send/Receive slowed do...

Updating an Event Sent
How do we change minor details of a meeting that's already on the Outlook calendar, without re-sending ("send update") the meeting to everyone? Quite often we just want to make a spelling correction, change mtg accommodations, or add instructions in the note portion that our receptionist can read about setting up the room etc. i.e. "Don't forget that Joe Smith likes Diet Soda". However, we don't want to re-send the message to anyone because people get confused! Outlook 2007 only gives 2 choices now "Don't Save Changes" or "Save...

Adding a Drop down menu to a column
Hello! Can anyone tell me how to add a drop down list to a specific column? I need to have only two options in the list, and the people using the spreadsheet should not be able to input any other value than: Local Market Other Thanks! Hi, Stacy. Try this: http://www.officearticles.com/excel/drop-down_using_data_validation_in_microsoft_excel.htm You can just type your two values in. ******************* ~Anne Troy www.OfficeArticles.com www.MyExpertsOnline.com "Stacy" <Stacy@discussions.microsoft.com> wrote in message news:CF8C3D65-513E-496C-A720-669E2ABD7ADE@micros...

Calendar events right on the screen, but print on duplicate/wrong date
Version: 2004 Operating System: Mac OS X 10.5 (Leopard) Processor: Intel Email Client: pop If I enter an all-day event on a Monday, it also shows up on the previous Wednesday - but only when I print the calendar. It does not show up wrong on the screen! Any ideas about what's causing this and how to fix it? ...

Event Sub when one specific cell changes
Hi, I am using Excel 2007. I have written a VBA Sub that I want to be called any time the value in one particular cell is changed. I know I can do this by creating a Worksheet_Change() Sub and checking the 'Target' Range parameter to see if the changed cell is the one I want to watch. The drawback of this is that this Sub gets called any time *any* cell is changed. In my case, this will get called alot because I have a value in another cell that changes once per second (it displays the current time). I was wondering if there is an event Sub other than Worksheet_...

Help please
The following error notification first appeared three days ago, but since then has been showing up in the event log about 50 times a day, at all times of day and night. I have made no changes to anything my end so what has triggered these apparent "attacks" and more over what do I need to do to stop them. They appear to come from all over the world unless they are spoofed. I list a few of the origins at the end of this post. Event ID: 4183 Source: MSExchangeIMC Type: Error Category. SMTP Interface Events Description: Authentication attempt (AUTH LOGIN) from 211.117.125.251...

Unable to get the window handle ... Windowless ActiveX controls are not supported
Hello, This exception : System.InvalidOperationException was caught Message="Unable to get the window handle for the 'AxMOSServer' control. Windowless ActiveX controls are not supported." Source="System.Windows.Forms" StackTrace: at System.Windows.Forms.AxHost.EnsureWindowPresent() at System.Windows.Forms.AxHost.InPlaceActivate() at System.Windows.Forms.AxHost.TransitionUpTo(Int32 state) at System.Windows.Forms.AxHost.CreateHandle() at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible) ...

qzip_detect.php pop-up box
I am so at a loss here. I run Windows XP Home, Service Pack 3, IE version 8, all updates up-to-date. Lately, in the past 24 hours or so, out of nowhere, I will be doing something and this pop-up will appear, almost constantly, for qzip_detect.php, and since of course it's not happening now, it asks if I would like to run the program or look for it and it says 0%. Does anyone know why this could be happening and how to stop it? Thanks. Lori wrote: > I am so at a loss here. I run Windows XP Home, Service Pack 3, IE version 8, > all updates up-to-date. Lately, i...

How do you create a drop-down menu within a cell in Excel?
How do you create a drop-down menu within a cell in Excel? You can use data validation. There are instructions in Excel's Help, and here: http://www.contextures.com/xlDataVal01.html Jimmy wrote: > How do you create a drop-down menu within a cell in Excel? -- Debra Dalgleish Excel FAQ, Tips & Book List http://www.contextures.com/tiptech.html ...

Another date handling question variant
Hi, I want to specify time+date and adjust them by timezone, but cannot see how to do this without laborious formulae. I've seen the other time/data tips on this site (v.good thanks), but they don't seem to cover this scenario. what I want to do: Column1: Time, format: dd-mmm-yy [hh]:mm eg: 26-feb-04 03:46 Column2: TZ offset, format: num (0 DP) eg: 5 Column3: Adjusted Time, format: dd-mmm-yy [hh]:mm formula: Col1 + (Col2/24) eg: 26-feb-04 08:46 ie. I want the basic number of TZ offset to increment the original time but that number of hours. Of course, it doesn't work, the e...