c++mfcresizecbutton

C++ MFC button disappears at window resize


I have a Dialog in MFC C++ that has a CButton attached. I want to modify OnSize() so that the button will anchor to bottom-left.

if (btn.m_hWnd) {
        CRect winRect;
        GetWindowRect(&winRect);

        int width = winRect.right - winRect.left;
        int height = winRect.bottom - winRect.top;

        int x = width - wndWidth;
        int y = height - wndHeight;


        CRect rect;
        btn.GetWindowRect(&rect);
        rect.left += x;
        rect.top += y;
        btn.MoveWindow(&rect);
        ScreenToClient(&rect);
        btn.ShowWindow(SW_SHOW);
    }

x and y are the difference of how much the window has changed and will be added to the button's start coordinates.

I am not sure about the last 2 commands (I might as well delete them) but then I run the program the button disappears.

I need to know a way to move the button by x and y.


Solution

  • The original code was using the wrong coordinate system for both the parent dialog, and the button.

    A correct way to dock to the bottom left would be like this:

    if (btn.m_hWnd) { 
        CRect winRect; 
        GetClientRect(&winRect); 
    
        CRect rect; 
        btn.GetWindowRect(&rect); 
        ScreenToClient(&rect); 
    
        int btnWidth = rect.Width();
        int btnHeight = rect.Width();
        rect.left = winRect.right-btnWidth; 
        rect.top  = winRect.bottom-btnHeight;
        rect.right = winRect.right;
        rect.bottom = winRect.bottom; 
        btn.MoveWindow(&rect); 
    }
    

    OR

    if (btn.m_hWnd) { 
        CRect winRect; 
        GetClientRect(&winRect); 
    
        CRect rect; 
        btn.GetWindowRect(&rect); 
        ScreenToClient(&rect); 
    
        int btnWidth = rect.Width();
        int btnHeight = rect.Width();
        btn.SetWindowPos(NULL,winRect.right-btnWidth,winRect.bottom-btnHeight,0,0,SWP_NOSIZE|SWP_NOZORDER);
    }