I have a number of buttons which are stored in a two dimensional array. How do I make the program to know what button I clicked on? Something like mouseClicked event in Java.
If you've created the button in the resources, it will have an ID (something like IDC_BUTTON1). This should then be added to a message map which will call a function when the parent class (e.g. your dialog) gets the BN_CLICKED message. This can be done in class wizard - Ctrl+W, Message Maps, highlight the object ID, find the BN_CLICKED message and "Add Function". This should add a function (for each button) to the dialog called something like OnButton() which will be called when BN_CLICKED is recieved for the buttons resource ID - i.e. the user clicks the button.
If all your buttons point to one resource object, you can add the message map in the normal way and to differentiate between buttons, you can create a class that inherits from CButton (Ctrl+W, Add Class, New, enter a class name and select CButton as the base class) and add an ID member variable which you can assign when you create the button object. When your OnButton() function is called, you can check the buttons ID to find out which one has been clicked.
Ok, when I came to do this, it was a bit more tricky than I'd anticipated. This solution isn't exactly as I said before, and it's a little messy but it does work (which is the main thing!).
anyway, here goes:
first, you create your CMyButton class and inherit from CButton. Your class declaration should look someting like this:
class CMyButton : public CButton
{
// Construction
public:
CMyButton();
// Attributes
public:
int m_nButtonID;
bool m_bIsClicked;
In the Dialog itself, you need to add a button (in resource view) and give it an ID, say, IDC_BUTTTON1. Then add it to the message map and create a funtion (as described in my previous post).
Add the following code to the message map function OnButton1():
void CTestDlg::OnButton1()
{
for(int x = 0; x <= 1; x++)
{
for(int y = 0; y <= 1; y++)
{
if(buttons[x][y].IsClicked())
{
//it's this one [x][y]
int id = buttons[x][y].m_nButtonID;
}
}
}
}
CMyButton::m_bIsClicked is set to true in CMyButton::OnLButtonDown(). When you call CMyButton::IsClicked(), it's set to false again so there should be no confusion about which button is the one you want.
Originally, I thought you'd be able to ascertain which button was being clicked by calling GetDlgItem(IDC_BUTTON1) in the dialogs message map function, but it seems that MFC binds the IDC_BUTTON1 id to a control and it can't be shared, hence the change of plan.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.