Search code examples
c++visual-studiovisual-c++mfcdirect2d

Why is my mouse cursor coordinates suddenly scaled?


At the beginning, sorry about my English.

I'm now learning how to build a MFC application in visual studio 2015. I'm using Direct2D to draw lines in a window.

When left button is down, my OnLbuttonDown() function is called:

void CMyProjectNameView::OnLButtonDown(UINT nFlags, CPoint point)
{
    startPoint = point;   // start point of the line, a gloable variable.
    pRenderTarget->BeginDraw();
    CView::OnLButtonDown(nFlags, point);
}

When left button is up, my OnLButtonUp() function is called:

void CMyProjectNameView::OnLButtonUp(UINT nFlags, CPoint point)
{
    pRenderTarget->DrawLine(startPoint, point, m_pbrush, 1.0f); // draw the line
    pRenderTarget->EndDraw();
    CView::OnLButtonUp(nFlags, point);
}

So it will draw a line in the window when I drag my mouse, and it works fine yesterday.

The problem is when I run it today, it suddenly become abnormal. The start point coordinates and end point coordinates is two times bigger than before. So When I draw the line, the line shows on the bottom right position compared to the position it supposed to be.

For instance, if I draw a line from (100,100) to (500,500), a line start from (100,100) to (500,500) will appear on screen, but when I click left button of my mouse at (100,100), move it to (500,500) and release left button, a line from (200,200) to (1000,1000) will be drawn.

OnLButtonDown(UINT nFlags, CPoint point)
OnLButtonUp(UINT nFlags, CPoint point)

So basically, these two point above is scaled before they are passed in. Do I accidentally change any configurations? Is there any way to fix this? I am sure I didn't change my code.


Solution

  • Coordinates for DrawLine are in device-Independent pixels. See also DPI and Device-Independent Pixels

    You have probably changed the size of client rectangle, it needs to be adjusted. Try also to resize the window and see if it gets the right coordinates.

    CRect rc;
    GetClientRect(&rc);
    
    D2D1_SIZE_F size = pRenderTarget->GetSize();
    const float x = size.width / rc.right;
    const float y = size.height / rc.bottom;
    
    D2D1_POINT_2F p1;
    D2D1_POINT_2F p2;
    
    p1.x = 100 * x;
    p1.y = 100 * y;
    
    p2.x = 500 * x;
    p2.y = 500 * y;
    
    pRenderTarget->DrawLine(p1, p2, brush);