简体   繁体   中英

create a control programmatically using MFC

I just wonder how to do it. I write :

CEdit m_wndEdit;

and in the button event handler (dialog app), I write :

m_wndEdit.Create(//with params);

but I still don't see the control appear in the UI.

I actually wrote this in the button handler :

CWnd* pWnd = GetDlgItem(IDC_LIST1);
CRect rect;

pWnd->GetClientRect(&rect);

//pWnd->CalcWindowRect(rect,CWnd::adjustBorder);

wnd_Edit.Create(ES_MULTILINE | ES_NOHIDESEL | ES_READONLY,rect,this,105);

wnd_Edit.ShowWindow(SW_SHOW);

this->Invalidate();

id 105 doesn't exist. (I used it in the Create member function of CEdit ). I just put it in there. isn't it supposed to be the id you want to give to the new control ? Should it already exist ?

Check with the following set of flags as the example mentioned in MSDN :

   pEdit->Create(ES_MULTILINE | WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER | ES_NOHIDESEL | ES_READONLY,
      rect, this, 105);
  • The Invalidate() is not necessary

  • Add the WS_VISIBLE flag to your create flags, you don't need the ShowWindow

  • You are creating the button on the location where IDC_LIST1 is - you probably want to do pWdn->Destroy() after the GetClientRect()

  • The id you pass to Create() can be anything, of course if you want to handle messages from this button later you'll need to use the correct id. In that case it's easiest to manually add an entry to resource.h.

  • What do you mean with 'I put this code in the button event handler' - which button? A different one from the one you're trying to create, I may hope? Does your code get called at all, does it stop when you put a breakpoint in? What's the value of wnd_Edit->m_hWnd after the call to Create()?

  • wnd_Edit is a member of your dialog, right, and not aa function local variable?

What is wnd_Edit exactly? If it's a local variable in that function, that is likely the problem. The CWnd destructor destroys the window associated with the CWnd. So when wnd_Edit goes out of scope, the edit box is destroyed too. If that's not it, check the return value of Create(). Is it NULL? If it is, check the value of GetLastError().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM