Dynamically creating controls in MFC (collection issue)

I have my own user control inside which I have to create radio objects or flags. The number of child controls is available only at runtime (it loads some file from which it receives this account). Therefore, I need to create a variable number of controls. What collection should I use for this purpose?

Solution 1: just use std::vector<HWND> (or CArray<HWND> ) - not suitable because I want to use MFC (CButton). Of course, I can Attach() and later Detach() access the window every time I need this window, but it will give a lot of overhead.

Solution 2: use std::vector<CButton*> or CArray<CButton*> or CList<CButton*> or ... In this case, I will take care of creating a "new" and corresponding "delete" when the control is not used. I will forget :)

The MFC descriptor map contains a pointer to CButton, and I cannot use a simple CArray<CButton> , because it will move my objects every time its size grows.

... and the question arises: What collection should I use to store variable counters of MFC management classes?

+4
source share
1 answer

If you want to read only the file with the Count parameter, create your buttons, work with them, and then delete them all, and then CArray<CButton*> in my opinion. To make sure the buttons are removed, you can bind CArray to a helper, for example:

 class CMyButtonArrayWrapper { public: CMyButtonArrayWrapper(); virtual ~CMyButtonArrayWrapper(); void ClearArray(); void Add(CButton* theButton); private: CArray<CButton*> m_Array; } CMyButtonArrayWrapper::CMyButtonArrayWrapper() { } CMyButtonArrayWrapper::~CMyButtonArrayWrapper() { ClearArray(); } void CMyButtonArrayWrapper::ClearArray() { for (int i=0; i<m_Array.GetSize(); i++) { CButton* aButton=m_Array.GetAt(i); if (aButton) delete aButton; } m_Array.RemoveAll(); } void CMyButtonArrayWrapper::Add(CButton* theButton) { m_Array.Add(theButton); } 

Then add an object of this class as an element to your custom control ( m_MyButtonArrayWrapper ) and add your buttons with:

 CButton* aButton=new CButton; aButton->Create( ... ); m_MyButtonArrayWrapper.Add(aButton); 

If you need to add and remove buttons at random, CList may be better suited for performance reasons. (But you probably won't notice the performance difference with InsertAt / RemoveAt from CArray, except that your user interface has several thousand buttons. I think that would be more a cover than a user interface :))

+2
source

Source: https://habr.com/ru/post/1305830/


All Articles