【问题标题】:call onPaint() with button click通过单击按钮调用 onPaint()
【发布时间】:2013-10-02 06:00:52
【问题描述】:

我在对话框中有一个图片控制框(CStatic)。当用户在对话框中按下按钮时,我需要 onPaint() 在其中绘制图像。问题是,图像是在加载对话框时绘制的。如何防止这种情况发生并仅在按下按钮时调用它。

我的 onPaint 代码;

void CStaticGraph::OnPaint()
{
    POINT xy[1000];
    CPaintDC dc(this); // device context for painting

    CRect Recto;
    char LocDim[80];

    GetWindowRect(&Recto);

    CPoint pBottom,pTop,pLeft;
    CPoint p[50];


    pBottom.SetPoint(0,0);
    pTop.SetPoint(0,Recto.Height());
    pLeft.SetPoint(Recto.Width(),Recto.Height());

    dc.MoveTo(pBottom);
    dc.LineTo(pTop);
    dc.LineTo(pLeft);

    int y[] ={80,120,180,200};
    int x=0;
    for(int i=0; i<sizeof(y);i++){
        p[i].SetPoint(Recto.Height()-x,y[i]);
        if(i>0){
                dc.MoveTo(p[i-1]);
                dc.LineTo(p[i]);


        }
        x+=50;
    }
}

如您所见,我正在绘制图表,我还需要在按下按钮时传递数据(y[] 值)。我还没有这样做。
谢谢。

【问题讨论】:

  • 我的建议是创建一个 ActiveX 控件(使用 MFC 或 ATL),然后将该控件嵌入到您的对话框中。通过向按钮发送数据来响应按钮,此时它会绘制图形。
  • sizeof() 为您提供数组中的总字节数,而不是元素数。使用 VisualStudio,您应该可以使用 _countof() 宏来获取 elelements 的数量。

标签: c++ visual-c++ visual-studio-2008 mfc onpaint


【解决方案1】:

向您的 CStaticGraph 类添加一个变量,例如 BOOL,作为一个标志来告诉 OnPaint() 做什么。在构造函数中初始化变量并在单击按钮时更改它。例如:

在 CStaticGraph 的头文件中添加:

BOOL    m_fButtonPressed;

在 CStaticGraph 构造函数中添加:

m_fButtonPressed = FALSE;

在您的按钮单击处理程序中执行以下操作:

void CStaticGraph::OnButtonClick()
{
  m_fButtonPressed = TRUE;
  Invalidate();
}

然后在您的 OnPaint 中仅在设置标志时绘制图形:

void CStaticGraph::OnPaint()
(
  CPaintDC dc(this);

  if ( m_fButtonPressed )
  {
    // Clear the window
    return;
  }

  // Draw the graph
  . . .
}

【讨论】:

    【解决方案2】:

    除了另一个答案中的Invalidate(),你还需要更改

    for(int i=0; i<sizeof(y);i++)
    

    for(int i=0; i<sizeof(y)/sizeof(int);i++)
    

    【讨论】:

    • 为什么?我以为 sizeof(y) 返回数组的大小?
    • 根据MSDN doc., When the sizeof operator is applied to an array, it yields the total number of bytes in that array... -- 你可以在调试器中查看值...
    猜你喜欢
    • 2017-10-01
    • 2019-02-28
    • 1970-01-01
    • 2017-01-13
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 2019-10-03
    相关资源
    最近更新 更多