C++ – How to recreate style used by resource editor when creating MFC controls dynamically

cmfc

I need to create some controls in a MFC dialog dynamically. The creation works fine so far, but the controls created dynamically are looking different from controls created with the resource editor. Some controls even behave different. I think, that I'm missing some initializations the generated code does.

Currently I only create CStatic and CEdit controls. Both don't use the standard windows font when I create them dynamically (the font looks more like the default font used prior to Windows 95, if I remember correctly).

Also, the CEdit control behaves different from when I create it with the resource editor. The dynamically created control seems to limit the text length to the visible size. I can set a longer text with SetWindowText() and read the full text back in with GetWindowText(), but the user can't enter a text longer than the size displayed. The CEdit control created by the resource editor behaves different: If the user enters a text longer than what can be displayed, the entered text ist "scrolled" inside the control (no scrollbars, as its only a single line control).

I tried fixing that problem by calling SetLimitText() on the control, but that didn't change the behavior.

The controls are saved to arrays defined in the dialog-class:

CStatic** m_pLabels;
CEdit**   m_pEdits;

The creation of the controls happens in the OnInitDialog() method of the dialog-class:

for (int i = 0; i < max; i++)
{
  m_pLabels[i] = new CStatic();
  m_pLabels[i]->Create("key", WS_CHILD | WS_VISIBLE | SS_RIGHT,
    CRect(10, 10 + i * 30, 130, 35 + i * 30), this);

  m_pEdits[i] = new CEdit();
  m_pEdits[i]->CreateEx(WS_EX_CLIENTEDGE, "EDIT", "",
    WS_CHILD | WS_TABSTOP | WS_VISIBLE | WS_BORDER,
    CRect(133, 10 + i * 30, 350, 35 + i * 30), this, i + 100);
  m_pEdits[i]->SetLimitText(499);
  m_pEdits[i]->SetWindowText("value to be edited");
}

Thanks for your help!

Best Answer

Dynamically created controls always get the stock font initially: the usual approach is to just set the control's font to the parent dialog's font: something like

  pEdits[i]->SetFont(GetFont());