draw simple rectangle in MFC Dialog-Based

11.1k Views Asked by At

I wrote this code to draw a simple rectangle in a dialog , I also added ON_WM_PAINT() to my message map. but it didnt show anything on dialog to me ! I really appreciate it if anyone could tell my mistakes in code:

void Ctest4Dlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting
        // TODO: Add your message handler code here

        SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = 2;
        int y = 2;

        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);

        //I want to draw a rectangle 
        dc.Rectangle(10,10,50,50);
    }
    else
    {
        CDialogEx::OnPaint();
    }
}
2

There are 2 best solutions below

7
Jerry Coffin On

Your first and biggest mistake is trying to draw directly in a dialog. While it is possible to do so, it's almost always a bad idea. A dialog should usually be treated as a container for controls.

0
Jonathan Wood On

Looks like your paint code only runs when the window is iconic? Why are you doing that?

Put it in the else block, after the call to CDialogEx::OnPaint().