c++visual-studiouser-interfacemfccbutton

Get CButton control name from resource id?


I am using C++ MFC, and have created a simple dialog with CButtons, each of them mapped with its .bitmap files and resource ids (ID_BUTTON*) in a .rc script file.

Similar lines are present in my .rc file, in DIALOG description:

CONTROL         "TEST|Button7",ID_BUTTON2,"Button",BS_OWNERDRAW | WS_TABSTOP,234,29,30,71

In my project I am trying to get the resource id of each CButton object. I did it with this:

int getID = this->GetDlgCtrlID();

But how can I use my resource ID further to get the CButton control text value? Meaning this:

"TEST|Button7"

If not, is there a specific way to get it?


Solution

  • It's actually very simple. Where you use int getID = this->GetDlgCtrlID(); to get the resource ID, you can use this code to get the control's name:

    CString buttonName;
    this->GetWindowText(buttonName);
    

    PS: Assuming the calls are made inside a class member function, then you don't actually need the this-> pointer; just call the GetWindowText() or GetDlgCtrlID() functions. (But using this-> does no harm, and can make code a bit clearer to read.)

    If you want to get the text for a button from outside the button's own class functions - say, from the parent dialog box handler, you can use this:

    CString buttonName;
    GetDlgItem(idValue)->GetWindowText(buttonName);
    

    Where idValue is the resource ID of the button (or any other control) concerned.