VC++ custom control establishment and use methods

  • 2020-04-02 03:04:56
  • OfStack

One, VC++ definition of custom controls and Delphi,VB some differences.

Delphi,vb in the file-new-other. Vc++ in the toolbar has a custom control, but must join the control type.

Many books are created in the class wizard. I'm talking about manual setup here, and the result is the same.

Ii. Custom control type established:

    2.1 put the custom control on the toolbar into the dialog box
    2.2 establish mycontrol. h and mycontrol. CPP files
    2.3 the definition in mycontrol. h is


#ifndef __MYCTROLTRL_H__
  #define __MYCTROLTRL_H__
  #define MYWNDCLASS "mycontrol"
  #include <afxtempl.h>
  class CMycontrol: public CWnd
  {
   private:
   public:
   static BOOL RegisterWndClass();
   CMycontrol();
   void customfun();//A custom method
   };
  #endif

      2.4 implementation in mycontrol.cpp


#include "StdAfx.h"
  #include "mycontrol.h"
  CMycontrol::CMycontrol()
  {
 CMycontrol::RegisterWndClass();
  }
  //Register control RegisterWndClass format is fixed do not remember without the need to directly copy and paste.
  CMycontrol::RegisterWndClass()
  {
  WNDCLASS windowclass;
  HINSTANCE hInst = AfxGetInstanceHandle();
  //Check weather the class is registerd already
  if (!(::GetClassInfo(hInst, MYWNDCLASS, &windowclass)))
  {
    //If not then we have to register the new class
    windowclass.style = CS_DBLCLKS;// | CS_HREDRAW | CS_VREDRAW;
    windowclass.lpfnWndProc = ::DefWindowProc;
    windowclass.cbClsExtra = windowclass.cbWndExtra = 0;
    windowclass.hInstance = hInst;
    windowclass.hIcon = NULL;
    windowclass.hCursor = AfxGetApp()->LoadStandardCursor(IDC_ARROW);
    windowclass.hbrBackground = ::GetSysColorBrush(COLOR_WINDOW);
    windowclass.lpszMenuName = NULL;
    windowclass.lpszClassName = MYWNDCLASS;
    if (!AfxRegisterClass(&windowclass))
    {
      AfxThrowResourceException();
      return FALSE;
    }
  } 
  return TRUE;
 }
 //Custom method
 void CMycontrol::customfun()
 {
 AfxMessageBox(_T("my control!"));
 }

Use custom controls

      3.1. You won't find the type you just defined when binding custom controls in the class wizard, so I added the code method manually.
      3.2. Add: public: CMycontrol m_mycontrol manually in the dialog box. H file;
      3.3. Manually add DDX_Control(pDX,IDC_CUSTOM1,m_mycontrol) in the dialog box.
      3.4. Add Button in the dialog box and add test code in the click event:


void CCustomcontrolDlg::OnButton1()
  {
 // TODO: Add your control notification handler code here
   m_mycontrol.customfun(); 
 }

Compile and run vc++ custom control dialog box form

Right-click custom control - > Property - > Type "mycontrol" again allows OK!

To this VC++ custom control is all introduced, you can add you want to implement methods in the type.

The above is all the content of this article, I hope you can enjoy it.


Related articles: