Fix mouse getting grabbed outside window of the game

This commit is contained in:
KKNecmi 2026-03-06 01:22:49 +03:00
parent eed770b121
commit a3b9f0f2cd
3 changed files with 44 additions and 11 deletions

View file

@ -4,6 +4,7 @@
#include "KeyboardMouseInput.h" #include "KeyboardMouseInput.h"
#include <cmath> #include <cmath>
#include <windows.h>
KeyboardMouseInput g_KBMInput; KeyboardMouseInput g_KBMInput;
@ -125,16 +126,40 @@ void KeyboardMouseInput::Tick()
} }
} }
if ((m_mouseGrabbed || m_cursorHiddenForUI) && g_hWnd) #ifdef _WINDOWS64
{ if (!IsGameInFront())
RECT rc; {
GetClientRect(g_hWnd, &rc); ClipCursor(NULL);
POINT center; while (ShowCursor(TRUE) < 0) {}
center.x = (rc.right - rc.left) / 2; }
center.y = (rc.bottom - rc.top) / 2; else if (m_cursorHiddenForUI)
ClientToScreen(g_hWnd, &center); {
SetCursorPos(center.x, center.y); ClipCursor(NULL);
} }
else if (m_mouseGrabbed && g_hWnd)
{
ClipCursorToWindow(g_hWnd);
RECT rc;
GetClientRect(g_hWnd, &rc);
POINT center;
center.x = (rc.right - rc.left) / 2;
center.y = (rc.bottom - rc.top) / 2;
ClientToScreen(g_hWnd, &center);
SetCursorPos(center.x, center.y);
}
#else
if ((m_mouseGrabbed || m_cursorHiddenForUI) && g_hWnd)
{
RECT rc;
GetClientRect(g_hWnd, &rc);
POINT center;
center.x = (rc.right - rc.left) / 2;
center.y = (rc.bottom - rc.top) / 2;
ClientToScreen(g_hWnd, &center);
SetCursorPos(center.x, center.y);
}
#endif
} }
void KeyboardMouseInput::OnKeyDown(int vkCode) void KeyboardMouseInput::OnKeyDown(int vkCode)
@ -408,4 +433,10 @@ void KeyboardMouseInput::ClearCharBuffer()
m_charBufferTail = 0; m_charBufferTail = 0;
} }
bool KeyboardMouseInput::IsGameInFront()
{
HWND InFrontWindow = GetForegroundWindow();
return (InFrontWindow == g_hWnd);
}
#endif // _WINDOWS64 #endif // _WINDOWS64

View file

@ -139,6 +139,8 @@ private:
wchar_t m_charBuffer[CHAR_BUFFER_SIZE]; wchar_t m_charBuffer[CHAR_BUFFER_SIZE];
int m_charBufferHead; int m_charBufferHead;
int m_charBufferTail; int m_charBufferTail;
bool IsGameInFront();
}; };
extern KeyboardMouseInput g_KBMInput; extern KeyboardMouseInput g_KBMInput;

View file

@ -1,7 +1,7 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.14.37012.4 d17.14 VisualStudioVersion = 17.14.37012.4
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Minecraft.World", "Minecraft.World\Minecraft.World.vcxproj", "{F046C3CE-9749-4823-B32B-D9CC10B1A2C8}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Minecraft.World", "Minecraft.World\Minecraft.World.vcxproj", "{F046C3CE-9749-4823-B32B-D9CC10B1A2C8}"
EndProject EndProject