Programming |  Windows |  subject

In this example, the mouse is captured in response to the left button down message. LoadCursor and SetCursor are used to change the cursor to a crosshair. A member of the c++ class that holds information about the window is used to hold the mouse's position. Another member of the class is used to make note that the mouse is captured. SetCapture is then called to grab the mouse.

During the mouse-move messages, the change in position is calculated and used to change the position of the thing being moved through the move_rel method. This method also invalidates the thing's old and new bounding rectangles, which in turn forces Windows to re-paint the place where the thing was, and where the thing is now.

In response to the left button up message, the thing is moved one last time, the cursor restored to the former cursor, and mouse released with ReleaseCapture.

Handling the Left Mouse Button Down Message

//####################################################################################
void graphic_window::on_lbutton_down(HWND hwnd, BOOL doubleclick, int x, int y, UINT keyflags)
{
    int controller_point_hit;

    scrn_point_hit.x = x;
    scrn_point_hit.y = y;

    if (hit_gpoint = hit_test_graphic_point(scrn_point_hit)) {
        dbgprintf("graphic_window::on_lbutton_down at %d, %d\n", x, y);
        SetCursor(LoadCursor(NULL, IDC_CROSS));
        SetCapture(hwnd);
        moving_point = true;
    }
    else if (hit_gtext = hit_test_graphic_text(scrn_point_hit)) {
        dbgprintf("graphic_window::on_lbutton_down at %d, %d\n", x, y);
        SetCursor(LoadCursor(NULL, IDC_CROSS));
        SetCapture(hwnd);
        moving_text = true;
    }
}

Handling the Mouse Move Message

//####################################################################################
void    graphic_window::on_mouse_move(HWND hwnd, int x, int y, UINT keyFlags)
{
    if (moving_point) {
        hit_gpoint->move_rel(hwnd, x - scrn_point_hit.x, y - scrn_point_hit.y);
        scrn_point_hit.x = x;
        scrn_point_hit.y = y;
    }
    else if (moving_text) {
        hit_gtext->move_rel(hwnd, x - scrn_point_hit.x, y - scrn_point_hit.y);
        scrn_point_hit.x = x;
        scrn_point_hit.y = y;
    }
}

Handling the Left Mouse Button Up Message

//####################################################################################
void graphic_window::on_lbutton_up(HWND hwnd, int x, int y, WPARAM keyflags)
{
    dbgprintf("graphic_window::on_lbutton_up at %d, %d\n", x, y);
    if (moving_point) {
        hit_gpoint->move_rel(hwnd, x - scrn_point_hit.x, y - scrn_point_hit.y);
        ReleaseCapture();
        SetCursor(LoadCursor(NULL, IDC_ARROW));
        moving_point = false;
    }
    else if (moving_text) {
        hit_gtext->move_rel(hwnd, x - scrn_point_hit.x, y - scrn_point_hit.y);
        ReleaseCapture();
        SetCursor(LoadCursor(NULL, IDC_ARROW));
        moving_text = false;
    }
}