Search code examples
windowsvisual-c++win32gui

coordinate calculation program


I want to make a simple coordinate calculation program for windows : application

Can move X_Line (Red) and Y_Line (Blue) by left click mouse and show coordinates.

But I need help to make coordinates part and functions for this scenario.

Please help me to any part of the program that you can !?!

Thank for your help,


Solution

  • Handle WM_LBUTTONDOWN and record mouse position, then send a paint message to paint at that coordinate.

    #include <Windows.h>
    
    LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wparam, LPARAM lparam)
    {
        static int xcoord = -1;
        static int ycoord = -1;
        switch(msg)
        {
        case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hWnd, &ps);
    
            if(xcoord >= 0 && ycoord >= 0)
            {
                RECT rc;
                GetClientRect(hWnd, &rc);
    
                //draw horizontal line
                MoveToEx(hdc, 0, ycoord, NULL);
                LineTo(hdc, rc.right, ycoord);
    
                //draw vertical line
                MoveToEx(hdc, xcoord, 0, NULL);
                LineTo(hdc, xcoord, rc.bottom);
            }
    
            EndPaint(hWnd, &ps);
            return 0;
        }
    
        case WM_LBUTTONDOWN:
        {
            xcoord = ((int)(short)LOWORD(lparam));
            ycoord = ((int)(short)HIWORD(lparam));
            InvalidateRect(hWnd, NULL, TRUE);
            return 0;
        }
    
        case WM_DESTROY:
    
            PostQuitMessage(0);
            return 0;
        }
    
        return DefWindowProc(hWnd, msg, wparam, lparam);
    }
    
    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR, int)
    {
        WNDCLASSEX wcex = { sizeof(WNDCLASSEX) };
        wcex.lpfnWndProc = WndProc;
        wcex.hInstance = hInstance;
        wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
        wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
        wcex.lpszClassName = TEXT("classname");
        RegisterClassEx(&wcex);
    
        CreateWindow(wcex.lpszClassName, NULL, WS_VISIBLE | WS_OVERLAPPEDWINDOW,
            0, 0, 600, 400, 0, 0, hInstance, 0);
    
        MSG msg;
        while(GetMessage(&msg, NULL, 0, 0))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    
        return (int)msg.wParam;
    }