c#中的Win api.MouseMove事件不能捕捉快速移动

本文关键字:移动 不能 事件 中的 Win api MouseMove | 更新日期: 2023-09-27 18:12:30

我用c#中的WinApi函数创建了一个没有边框的小窗口。我想在按下鼠标右键时移动此窗口。我试图通过分析WM_MOUSEMOVE事件来捕获鼠标偏移。它似乎工作,我可以移动我的窗口持有鼠标右键。

但是当我移动鼠标太快时,我正在失去对窗口的控制。那是因为我的窗口太小了,如果鼠标离开窗口非常快,它不再接收WM_MOUSEMOVE消息,我不能计算鼠标偏移来移动我的窗口。

那么,我该如何解决这个问题呢?

c#中的Win api.MouseMove事件不能捕捉快速移动

您需要调用SetCapture来告诉Windows,即使鼠标不在窗口上,您的hwnd也需要所有事件。http://msdn.microsoft.com/en-us/library/windows/desktop/ms646262 (v = vs.85) . aspx

你可以告诉Windows用户已经在标题栏上按下鼠标,它会自动为你处理剩下的。

[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ReleaseCapture();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
internal const uint WM_NCLBUTTONDOWN = 0xA1;
internal const int HTCAPTION = 2; // Window captions
internal const int HTBOTTOMRIGHT = 17; // Bottom right corner
/// <summary>
/// Simulates a Windows drag on the window border or title.
/// </summary>
/// <param name="handle">The window handle to drag.</param>
/// <param name="dragType">A HT* constant to determine which part to drag.</param>
internal static void DragWindow(IntPtr handle, int dragType) {
    User32.ReleaseCapture();
    User32.PostMessage(handle, User32.WM_NCLBUTTONDOWN, new IntPtr(dragType), IntPtr.Zero);
}