• 10
• 13
• 18
• 27
• 9

Windows API - Listbox control - finding out what's selected?

This topic is 3956 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

The Windows API is definitely not one of my strong points, but having to create an editor for my game, I've been working with it again a little (in C++ of course). I did a lot of searching in attempts to find the solution to the problem myself, but my research has come up short. Most stuff on Google about listboxes seems to deal with VB or other languages, and the relevant stuff I did find.. well, just didn't work. On with the question... It's very simple, don't let the long paragraphs fool you (I just try to explain my situation as clearly as possible): I have a listbox in my dialog box. When a listbox item is selected, I need some code to be executed. So, I have the messages in place (with LBN_SELCHANGE and whatnot), so I do know WHEN a listbox item is being selected. But I can't get the code to figure out WHICH item is being selected. Now, in earlier code, when items were added to the list, I saved the indexes. When you're adding entries to the listbox list, SendMessage() returns an int which is the "index" of the listbox entry. So I have those indexes all stored away to know which index relates to which set of data... So I need some code that will basically find the index of the selected listbox entry. After researching the LB_GETSELITEMS message, here's what I tried, but it does NOT work:
		int * iSelectedID = (int*)GlobalAlloc(GPTR, sizeof(int));;
SendDlgItemMessage(hDlg, IDC_LISTBOX, LB_GETSELITEMS, (WPARAM)1, (LPARAM)iSelectedID);
The idea is that iSelectedID[0]'s value will be the index of the currently selected listbox item. Instead, that value is always 0. So, can anyone tell me what's wrong with the code? I can't find much relevant information on LB_GETSELITEMS with clear examples (only found one example, which is what I mostly based that earlier code off of).

Share on other sites
Use LB_GETCURSEL to retrieve the index of the selected item. LB_GETSELITEMS only works on multi selection listboxes (which the MSDN tells you when you look it up).

Also, you do not need to store an external additional list. For every item you can use the item data. This is big enough to carry a pointer; so you can either store a value or a pointer to something in there.

You can access the item data via LB_SETITEMDATA and LB_GETITEMDATA.