简体   繁体   English

CButton:当使用SetState时,不可预见地调用OnBnClicked()

[英]CButton : OnBnClicked() is called inexepectedly when SetState is used

I want to click a button and shown it "pressed" until a timer has terminated. 我想点击一个按钮并显示“按下”直到计时器终止。

The problem I have is, wenn I use CButton::SetState(TRUE) the function OnBnClickedButton1() is called always twice and even worse it is called again when I press a another button in the dialog or hide the dialog window. 我遇到的问题是,我使用CButton::SetState(TRUE)函数OnBnClickedButton1()总是被调用两次甚至更糟,当我按下对话框中的另一个按钮或隐藏对话框窗口时再次调用它。

(Update: I have now tested the same code at home under VS6 with WindowsXP, it works fine as expected. At work (VS2010 with Window 10) this code does not work.) (更新:我现在已经在VS6下使用WindowsXP在家中测试了相同的代码,它可以正常工作。在工作时(VS2010与Window 10),此代码不起作用。)

Header file 头文件

class CTestDialog : public CDialog
{
    CButton btnButton1;

    enum {eTimerCoolingId = 123};
    BOOL m_bCooling;
    DWORD m_dwStartTick;
    ...
}

CPP file CPP文件

...
DDX_Control(pDX, IDC_BUTTON1, m_btnButton1);

void CTestDialog::OnBnClickedButton1()
{
    m_bCooling = !m_bCooling;
    m_btnButton1.SetState(m_bCooling);
    m_dwStartTick = GetTickCount();

    if (m_bCooling)
        SetTimer(eTimerCoolingId,100,NULL);
    else
        KillTimer(eTimerCoolingId);
}

void CTestDlg::OnTimer(UINT nIDEvent) 
{
    int nCoolTime = 5;  // [sec]
    CString str;

    switch(nIDEvent)
    {
    case eTimerCoolingId:

        int nElapsedTime = (GetTickCount() - m_dwStartTick) / 1000;
        if (nElapsedTime > nCoolTime)
        {
            KillTimer(eTimerCoolingId);
            m_bCooling = false;
            m_btnButton1.SetState(FALSE);
            str.Format("Cooler On");
        }
        else
        {
            str.Format("Cooling.. %d [sec]", (nCoolTime - nElapsedTime));
        }
    }

   m_btnButton1.SetWindowText(str);
   CDialog::OnTimer(nIDEvent);
}

It's hopeless. 这是没有希望的。 SetState(TRUE) is very fishy and probably not indended for push like buttons. SetState(TRUE)非常可疑,并且可能没有按下按钮。 MSDN says: MSDN说:

"Set whether a button control is higilighted or not". “设置按钮控件是否高亮”。

I have tried it with different buttons (Nornal-, Radio-, CheckBox-, MFCButton). 我用不同的按钮(Nornal-,Radio-,CheckBox-,MFCButton)尝试过它。 For all of this buttons: SetState is forcing the message handler to be called again. 对于所有这些按钮:SetState强制再次调用消息处理程序。 (Don't know why!?) (不知道为什么!?)

I use now a Check-Box Button and set the push-like style. 我现在使用一个Check-Box按钮并设置推式样式。 And call CButton::SetCheck() instead of SetState(). 并调用CButton :: SetCheck()而不是SetState()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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