On Update command is not working for dynamically created button in MFC

696 Views Asked by At

In my code, i have added button in view class in OnCreate(). I included On Command and On Update COmmand funtionality. Here On command fucntion is working when i click the button. But On Update COmmand is not working. Im updating the pressing status of the button using this OnUpdateCommand().

In OnCreate()

rBar.left = 580;
    rBar.right = 620;
    cBZoomOut.Create("",WS_CHILD|WS_VISIBLE|BS_BITMAP ,rBar,this,IDC_TZOOMOUT);
    cBZoomOut.SetIcon(IDI_TZOOMOUT);

    rBar.left = 625;
    rBar.right = 665;
    cBZoomin.Create("",WS_CHILD|WS_VISIBLE|BS_BITMAP ,rBar,this,IDC_TZOOMIN);
    cBZoomin.SetIcon(IDI_TZOOMIN);

Message maps for those buttons.

    afx_msg void OnUpdateTzoomout(CCmdUI *pCmdUI);
    afx_msg void OnTzoomin();
    afx_msg void OnUpdateTzoomin(CCmdUI *pCmdUI);
    afx_msg void OnTzoomout();

    ON_UPDATE_COMMAND_UI(IDC_TZOOMOUT, &CTrendView::OnUpdateTzoomout)
    ON_COMMAND(IDC_TZOOMIN, &CTrendView::OnTzoomin)
    ON_UPDATE_COMMAND_UI(IDC_TZOOMIN, &CTrendView::OnUpdateTzoomin)
    ON_COMMAND(IDC_TZOOMOUT, &CTrendView::OnTzoomout)

On command and OnUpdatecommand function:

void CTrendView::OnTzoomout()
{   
    sTimeStatus.Format("<=>%d",Minute/2);

}
void CTrendView::OnUpdateTzoomout(CCmdUI *pCmdUI)
{   
    if (Minute == 16)
        pCmdUI->Enable(FALSE);
    else
        pCmdUI->Enable(TRUE);
}

In both Zoomin and Zoomout function, OnUpdateCommnad is not working.

2

There are 2 best solutions below

1
On

Try the following.

In TrendView.h add this:

afx_msg LRESULT OnKickIdle(WPARAM wParam, LPARAM lParam);

In TrendView.cpp add this:

#include <afxpriv.h>

...
ON_MESSAGE(WM_KICKIDLE, OnKickIdle)
...

LRESULT CTrendView::OnKickIdle(WPARAM wParam, LPARAM lParam)
{
    UpdateDialogControls(this, FALSE);
    return 0;
}
2
On

This routing isn't done automatically.

You have to handle WM_IDLEUPDATECMDUI. Usually you call the internal OnUpdateCmdUI virtual function. This finally calls UpdateDialogControls.

You find the details in TN021

Just set a breakpoint on a working OnUpdate Handler. And look into the call stack. Than you can see and imagine how the whole stuff works.

There is also a possible way to use WM_KICKIDLE and UpdateDialogControls. See this article.