The code I'm sending is Strafe Helper and it works perfectly. One problem is my mouse has low polling rate so its not smooth and I can't get high strafe efficiency. Could you add something in that will make my mouse move smoother as if I had higher polling rate? Send whole code.
#include <windows.h>
#include
#include
#include
// Function to simulate key press using scan codes
void PressKey(WORD scanCode) {
INPUT input = {};
input.type = INPUT_KEYBOARD;
input.ki.wScan = scanCode;
input.ki.dwFlags = KEYEVENTF_SCANCODE;
SendInput(1, &input, sizeof(INPUT));
}
// Helper class to manage key states
class KeyState {
public:
std::atomic aPressed;
std::atomic dPressed;
code
KeyState() : aPressed(false), dPressed(false) {}
void PressA() {
if (!aPressed.load()) {
PressKey(0x1E); // Scan code for 'A'
aPressed = true;
}
}
void ReleaseA() {
if (aPressed.load()) {
ReleaseKey(0x1E); // Scan code for 'A'
aPressed = false;
}
}
void PressD() {
if (!dPressed.load()) {
PressKey(0x20); // Scan code for 'D'
dPressed = true;
}
}
void ReleaseD() {
if (dPressed.load()) {
ReleaseKey(0x20); // Scan code for 'D'
dPressed = false;
}
}
void ReleaseAll() {
ReleaseA();
ReleaseD();
}
};
// Function to bring Roblox window to foreground
HWND GetRobloxWindow() {
HWND hwnd = FindWindow(NULL, NULL);
while (hwnd != NULL) {
wchar_t title[256];
GetWindowText(hwnd, title, sizeof(title) / sizeof(wchar_t));
std::wstring windowTitle(title);
if (windowTitle.find(L"Roblox") != std::wstring::npos) {
return hwnd;
}
hwnd = FindWindowEx(NULL, hwnd, NULL, NULL);
}
return NULL;
}
// Constants for thresholds and timings
const LONG MOVEMENT_THRESHOLD = 5; // Minimum pixels of movement before switching keys
const DWORD KEY_PRESS_DURATION = 10; // Minimum duration to hold a key in milliseconds
// Function to get the current time in milliseconds
DWORD GetCurrentTimeMs() {
return GetTickCount();
}
if (!isAdmin) {
std::cerr << "Please run the application as an administrator." << std::endl;
return 1;
}
const wchar_t CLASS_NAME[] = L"MouseCaptureWindow";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = GetModuleHandle(NULL);
wc.lpszClassName = CLASS_NAME;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
if (!RegisterClass(&wc)) {
std::cerr << "Failed to register window class." << std::endl;
return 1;
}
HWND hwnd = CreateWindowEx(
0,
CLASS_NAME,
L"Strafe Helper",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 300, 100,
NULL,
NULL,
GetModuleHandle(NULL),
NULL
);
if (hwnd == NULL) {
std::cerr << "Failed to create window." << std::endl;
return 0;
}
RAWINPUTDEVICE rid;
rid.usUsagePage = 0x01;
rid.usUsage = 0x02;
rid.dwFlags = RIDEV_INPUTSINK;
rid.hwndTarget = hwnd;
if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) {
std::cerr << "Failed to register raw input device." << std::endl;
return 1;
}
ShowWindow(hwnd, SW_SHOWMINIMIZED);
std::cout << "Strafe Helper is running.\n"
<< "Hold down the RIGHT mouse button and move the mouse left or right to strafe.\n"
<< "Press ESC to exit.\n";
std::atomic<bool> running(true);
std::thread exitThread([&running]() {
while (running.load()) {
if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) {
PostMessage(NULL, WM_CLOSE, 0, 0);
running = false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
});
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
running = false;
if (exitThread.joinable()) {
exitThread.join();
}
return 0;
}
Certainly! To improve the smoothness of your Strafe Helper by emulating a higher mouse polling rate, we can implement a separate thread that manages key state updates at a higher frequency. This approach ensures that even with a low mouse polling rate, the strafing action remains responsive and smooth.
Below is the modified complete code with detailed comments explaining the changes:
cpp
#include <windows.h>
#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>
// Function to simulate key press using scan codes
void PressKey(WORD scanCode) {
INPUT input = {};
input.type = INPUT_KEYBOARD;
input.ki.wScan = scanCode;
input.ki.dwFlags = KEYEVENTF_SCANCODE;
SendInput(1, &input, sizeof(INPUT));
}
// Function to simulate key release using scan codes
void ReleaseKey(WORD scanCode) {
INPUT input = {};
input.type = INPUT_KEYBOARD;
input.ki.wScan = scanCode;
input.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;
SendInput(1, &input, sizeof(INPUT));
}
// Helper class to manage key states
class KeyState {
public:
std::atomic<bool> aPressed;
std::atomic<bool> dPressed;
KeyState() : aPressed(false), dPressed(false) {}
void PressA() {
if (!aPressed.load()) {
PressKey(0x1E); // Scan code for 'A'
aPressed = true;
}
}
void ReleaseA() {
if (aPressed.load()) {
ReleaseKey(0x1E); // Scan code for 'A'
aPressed = false;
}
}
void PressD() {
if (!dPressed.load()) {
PressKey(0x20); // Scan code for 'D'
dPressed = true;
}
}
void ReleaseD() {
if (dPressed.load()) {
ReleaseKey(0x20); // Scan code for 'D'
dPressed = false;
}
}
void ReleaseAll() {
ReleaseA();
ReleaseD();
}
};
// Enum to represent strafing direction
enum class Direction {
None,
Left,
Right
};
// Shared atomic variable to store current direction
std::atomic<Direction> currentDirection(Direction::None);
// Function to bring Roblox window to foreground
HWND GetRobloxWindow() {
HWND hwnd = FindWindow(NULL, NULL);
while (hwnd != NULL) {
wchar_t title[256];
GetWindowText(hwnd, title, sizeof(title) / sizeof(wchar_t));
std::wstring windowTitle(title);
if (windowTitle.find(L"Roblox") != std::wstring::npos) {
return hwnd;
}
hwnd = FindWindowEx(NULL, hwnd, NULL, NULL);
}
return NULL;
}
// Constants for thresholds
const LONG MOVEMENT_THRESHOLD = 2; // Reduced threshold for smoother movimento
const DWORD KEY_UPDATE_INTERVAL = 5; // Interval in milliseconds for key updates
// Function to get the current time in milliseconds
DWORD GetCurrentTimeMs() {
return GetTickCount();
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
static bool isRightButtonDown = false;
static HWND robloxHwnd = NULL;
// Variables for cumulative mouse movement
static LONG cumulativeMouseX = 0;
switch (uMsg) {
case WM_INPUT: {
BYTE lpb[sizeof(RAWINPUT)];
UINT dwSize = sizeof(lpb);
if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize,
sizeof(RAWINPUTHEADER)) != dwSize) {
std::cerr << "GetRawInputData does not return correct size!" << std::endl;
break;
}
RAWINPUT* raw = (RAWINPUT*)lpb;
// Check if the right mouse button is held down
if (GetAsyncKeyState(VK_RBUTTON) & 0x8000) {
if (!isRightButtonDown) {
isRightButtonDown = true;
if (!robloxHwnd) {
robloxHwnd = GetRobloxWindow();
if (robloxHwnd) {
SetForegroundWindow(robloxHwnd);
}
else {
std::cerr << "Roblox window not found." << std::endl;
}
}
else {
SetForegroundWindow(robloxHwnd);
}
}
}
else {
if (isRightButtonDown) {
currentDirection = Direction::None;
}
isRightButtonDown = false;
cumulativeMouseX = 0; // Reset cumulative movement
break;
}
if (raw->header.dwType == RIM_TYPEMOUSE && isRightButtonDown) {
LONG deltaX = raw->data.mouse.lLastX;
// Accumulate mouse movement
cumulativeMouseX += deltaX;
// Determine direction based on cumulative movement
if (cumulativeMouseX >= MOVEMENT_THRESHOLD) {
currentDirection = Direction::Right;
cumulativeMouseX = 0; // Reset after determining direction
}
else if (cumulativeMouseX <= -MOVEMENT_THRESHOLD) {
currentDirection = Direction::Left;
cumulativeMouseX = 0; // Reset after determining direction
}
}
break;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
}
int main() {
BOOL isAdmin = FALSE;
PSID administratorsGroup = NULL;
SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;
if (AllocateAndInitializeSid(&ntAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
&administratorsGroup)) {
CheckTokenMembership(NULL, administratorsGroup, &isAdmin);
FreeSid(administratorsGroup);
}
if (!isAdmin) {
std::cerr << "Please run the application as an administrator." << std::endl;
return 1;
}
const wchar_t CLASS_NAME[] = L"MouseCaptureWindow";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = GetModuleHandle(NULL);
wc.lpszClassName = CLASS_NAME;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
if (!RegisterClass(&wc)) {
std::cerr << "Failed to register window class." << std::endl;
return 1;
}
HWND hwnd = CreateWindowEx(
0,
CLASS_NAME,
L"Strafe Helper",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 300, 100,
NULL,
NULL,
GetModuleHandle(NULL),
NULL
);
if (hwnd == NULL) {
std::cerr << "Failed to create window." << std::endl;
return 0;
}
RAWINPUTDEVICE rid;
rid.usUsagePage = 0x01;
rid.usUsage = 0x02;
rid.dwFlags = RIDEV_INPUTSINK;
rid.hwndTarget = hwnd;
if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) {
std::cerr << "Failed to register raw input device." << std::endl;
return 1;
}
ShowWindow(hwnd, SW_SHOWMINIMIZED);
std::cout << "Strafe Helper is running.\n"
<< "Hold down the RIGHT mouse button and move the mouse left or right to strafe.\n"
<< "Press ESC to exit.\n";
// Initialize KeyState
KeyState keyState;
// Atomic flag to control the running state
std::atomic<bool> running(true);
// Thread to handle key state updates for smooth strafing
std::thread keyThread([&keyState, &running]() {
while (running.load()) {
Direction dir = currentDirection.load();
if (dir == Direction::Left) {
keyState.PressA();
keyState.ReleaseD();
}
else if (dir == Direction::Right) {
keyState.PressD();
keyState.ReleaseA();
}
else {
keyState.ReleaseAll();
}
// Sleep for a short interval to emulate higher polling rate
std::this_thread::sleep_for(std::chrono::milliseconds(KEY_UPDATE_INTERVAL));
}
// Ensure all keys are released when the thread is stopping
keyState.ReleaseAll();
});
// Thread to listen for the ESC key to exit the application
std::thread exitThread([&running]() {
while (running.load()) {
if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) {
PostMessage(NULL, WM_CLOSE, 0, 0);
running = false;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
});
// Message loop
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Signal threads to stop and join them
running = false;
if (keyThread.joinable()) {
keyThread.join();
}
if (exitThread.joinable()) {
exitThread.join();
}
return 0;
}
Changes and Enhancements Explained
Direction Enum and Atomic Variable:
Enum: Added an enum class Direction to represent strafing directions (None, Left, Right).
Atomic Variable: Introduced an std::atomic<Direction> named currentDirection to safely share the strafing direction between threads.
Reduced Movement Threshold:
Threshold Adjustment: Lowered the MOVEMENT_THRESHOLD from 5 to 2 to respond to smaller mouse movements, enabling smoother strafing.
Separate Key Handling Thread:
Purpose: Created a new thread (keyThread) that runs independently of the main message loop to handle key presses and releases at a higher frequency.
Functionality: This thread continuously checks the currentDirection and updates the key states (A and D) accordingly.
Update Interval: Set to 5 milliseconds (KEY_UPDATE_INTERVAL) to emulate a higher polling rate, making strafing smoother.
KeyState Management:
Class Usage: The KeyState class remains responsible for managing the state of the A and D keys, ensuring that keys are not repeatedly pressed or released unnecessarily.
Thread Safety: The use of std::atomic<bool> within KeyState ensures thread-safe operations when updating key states from the separate thread.
Graceful Exit Mechanism:
Exit Thread: Added an exitThread that listens for the ESC key press to terminate the application gracefully.
Thread Joining: Ensured that both keyThread and exitThread are properly joined before the application exits, preventing potential threading issues.
Enhanced Responsiveness:
Foreground Window: Ensured that the Roblox window is brought to the foreground when strafing begins, improving responsiveness.
Usage Instructions
Compilation:
Ensure you have a C++ compiler that supports C++11 or later.
Compile the code with the necessary Windows libraries. For example, using g++:
Administrator Privileges: The application requires administrative privileges to simulate key presses. Run the executable as an administrator.
Operation:
Hold down the RIGHT mouse button.
Move the mouse left or right to strafe in the desired direction.
Press ESC to exit the application.
Additional Recommendations
Polling Rate Adjustment: If you still experience choppiness, consider adjusting the KEY_UPDATE_INTERVAL to a smaller value (e.g., 2 milliseconds) for even smoother updates. However, be cautious as very short intervals might increase CPU usage.
Key Press Optimization: Ensure that only one of the A or D keys is pressed at any given time to prevent conflicting inputs.
Error Handling: The current implementation includes basic error messages. For a production environment, consider implementing more robust error handling and logging mechanisms.
By implementing these changes, the Strafe Helper should provide a smoother strafing experience, effectively emulating a higher mouse polling rate even with a physically lower polling rate mouse.
Not yet included in a published release.
Cumulative Mouse Movement Reset: After determining the current direction based on mouse movement, the cumulative value is reset to allow for immediate response to new movements.