如何在不使用向导的情况下为控件(如编辑控件)手动添加控件变量并使用它



由于某种原因,"添加控制变量"向导在我的Visual Studio设置中不起作用("Microsoft Visual Studio Community 2019",版本16.1.16(。

那么,如何在代码中访问控制呢?设置、编辑控件和访问其数据需要哪些手动代码步骤?

下面是一些手动添加自己的控件和处理程序的简单步骤。

MyDlg.h

public:
   CButton m_Button;                    // your control
protected:
   virtual void DoDataExchange(CDataExchange* pDX);  // declare the data exchange support
   DECLARE_MESSAGE_MAP()             // your message map
public:
   afx_msg void OnBnClickedMyButton();  // your message handler

MyDlg.cpp

// do data exchange between your variable and the control
void MyDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, ID_BTN, m_Button);
}
// map your message with handler
BEGIN_MESSAGE_MAP(MyDlg, CDialogEx)
    ON_BN_CLICKED(ID_BTN, &MyDlg::OnBnClickedMyButton)
END_MESSAGE_MAP()
BOOL MyDlg::OnInitDialog(){
    /* … */
    m_Button.Create(L"Click-Me", WS_CHILD | WS_VISIBLE, RECT{ 0,0,100,100 }, this, ID_BTN);
    m_Button.ShowWindow(true);
}

最新更新