windows 如何使用其客户区实现拖动窗口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7773771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:16:38  来源:igfitidea点击:

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

c++windowswinapi

提问by May Oakes

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?

我有一个 Win32 HWND,我想允许用户保持控制和鼠标左键在屏幕上拖动窗口。鉴于 (1) 我可以检测到用户何时保持控制、鼠标左键和移动鼠标,以及 (2) 我有新旧鼠标位置,我如何使用 Win32 API 和我的 HWND 来更改窗户的位置?

回答by Hans Passant

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.

为 WM_NCHITTEST 实现消息处理程序。调用 DefWindowProc() 并检查返回值是否为 HTCLIENT。如果是,则返回 HTCAPTION,否则返回 DefWindowProc 返回值。您现在可以单击客户区并拖动窗口,就像单击标题拖动窗口一样。

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..
}