Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement dragging a window using its client area?

I have a Win32 HWND and I'd like to allow the user to hold control and the left mouse button to drag the window around the screen. Given (1) that I can detect when the user holds control, the left mouse button, and moves the mouse, and (2) I have the new and the old mouse position, how do I use the Win32 API and my HWND to change the position of the window?

like image 936
May Oakes Avatar asked Oct 14 '11 21:10

May Oakes


2 Answers

Implement a message handler for WM_NCHITTEST. Call DefWindowProc() and check if the return value is HTCLIENT. Return HTCAPTION if it is, otherwise return the DefWindowProc return value. You can now click the client area and drag the window, just like you'd drag a window by clicking on the caption.

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_NCHITTEST: {
        LRESULT hit = DefWindowProc(hWnd, message, wParam, lParam);
        if (hit == HTCLIENT) hit = HTCAPTION;
        return hit;
    }
    // etc..
}
like image 144
Hans Passant Avatar answered Oct 18 '22 01:10

Hans Passant


Sorry for being a little late to answer but here is the code you desire

First you declare these global variables:

bool mousedown = false;
POINT lastLocation;

bool mousedown tells us if user is holding left button on their mouse or not

Then in callback funtion you write these lines of code

case WM_LBUTTONDOWN: {
    mousedown = true;
    GetCursorPos(&lastLocation);
    RECT rect;
    GetWindowRect(hwnd, &rect);
    lastLocation.x = lastLocation.x - rect.left;
    lastLocation.y = lastLocation.y - rect.top;
    break;
}
case WM_LBUTTONUP: {
    mousedown = false;
    break;
}
case WM_MOUSEMOVE: {
    if (mousedown) {
        POINT currentpos;
        GetCursorPos(&currentpos);
        int x =  currentpos.x - lastLocation.x;
        int y =  currentpos.y - lastLocation.y;
        MoveWindow(hwnd, x, y, window_lenght, window_height, false);
    }
    break;
}
like image 2
552bb224 Avatar answered Oct 18 '22 02:10

552bb224