Kemal Tezer Dilsiz
Kemal Tezer Dilsiz

Reputation: 4009

How to get the current Tab Item name from CTabCtrl in MFC?

I am trying to get the text of the currently chosen tab in CTabCtrl.

    int tabCurSel = currentTabCtrl->GetCurSel();

    TCITEM tcItem;
    tcItem.mask = TCIF_TEXT;
    tcItem.cchTextMax = 256; //Do I need this?

    CString tabCurrentCString;
    currentTabCtrl->GetItem(tabCurSel, &tcItem);

    tabCurrentCString = tcItem.pszText;
    CT2A tabCurrentChar(tabCurrentCString);
    std::string tabCurrentStr(tabCurrentChar);
    return tabCurrentStr;

I clearly have some unnecessary string conversions and currently this returns a "Error reading characters of the string" in

    tcItem.pszText;

How can I get the string from the CTabCtrl? I ultimately am trying to get an std::string but the main question is how to get the text from the tab.

Upvotes: 1

Views: 2055

Answers (1)

Barmak Shemirani
Barmak Shemirani

Reputation: 31599

tcItem.pszText is pointing to 0. To fill it with text, it has to point to a buffer before a call is made to GetItem:

Documentation for: CTabCtrl::GetItem

pszText

Pointer to a null-terminated string containing the tab text if the structure contains information about a tab. If the structure is receiving information, this member specifies the address of the buffer that receives the tab text.

Example:

TCITEM tcItem { 0 };
tcItem.mask = TCIF_TEXT;
const int len = 256;
tcItem.cchTextMax = len; 
TCHAR buf[len] = { 0 };
tcItem.pszText = buf;
currentTabCtrl->GetItem(tabCurSel, &tcItem);

Both tcItem.pszText and buf will point to the same text. Or use CString with CString::GetBuffer()/CString::ReleaseBuffer()

CString tabCurrentCString;
TCITEM tcItem;
tcItem.mask = TCIF_TEXT;
tcItem.cchTextMax = 256; 
tcItem.pszText = tabCurrentCString.GetBuffer(tcItem.cchTextMax);
BOOL result = currentTabCtrl->GetItem(tabCurSel, &tcItem);
tabCurrentCString.ReleaseBuffer();

if (result)
    MessageBox(tabCurrentCString); //success

It looks like you are using the recommended Unicode settings. Avoid converting UNICODE to ANSI (std::string). This conversion will work for Latin languages, most of the time, but it's not needed. You can use std::wstring if you need to use that in STL, or convert to UTF-8 if you want to send data to internet etc.

std::string str = CW2A(tabCurrentCString, CP_UTF8);

Upvotes: 2

Related Questions