Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <Windows.h>
- #include <thread>
- #include <atomic>
- #include <chrono>
- #include <mutex>
- std::atomic<bool> isRunning(false);
- std::thread simulationThread;
- std::mutex simulationMutex;
- HWND currentWindowHandle = nullptr;
- void simulateSingleKeyPress(WORD key) {
- INPUT input = { 0 };
- input.type = INPUT_KEYBOARD;
- input.ki.wVk = key;
- SendInput(1, &input, sizeof(INPUT));
- input.ki.dwFlags = KEYEVENTF_KEYUP;
- SendInput(1, &input, sizeof(INPUT));
- }
- void keyPressTimer(WORD key, int delayMilliseconds) {
- while (true) {
- {
- std::lock_guard<std::mutex> lock(simulationMutex);
- if (!isRunning) break;
- }
- if (GetForegroundWindow() == currentWindowHandle) {
- simulateSingleKeyPress(key);
- }
- std::this_thread::sleep_for(std::chrono::milliseconds(delayMilliseconds));
- }
- }
- void startKeyPressSimulation(WORD key, int delayMilliseconds) {
- std::lock_guard<std::mutex> lock(simulationMutex);
- if (isRunning) {
- std::cout << "Simulation is already running.\n";
- return;
- }
- currentWindowHandle = GetConsoleWindow();
- if (!currentWindowHandle) {
- std::cout << "Failed to get the console window handle.\n";
- return;
- }
- isRunning = true;
- simulationThread = std::thread(keyPressTimer, key, delayMilliseconds);
- if (simulationThread.native_handle()) {
- SetThreadPriority(simulationThread.native_handle(), THREAD_PRIORITY_BELOW_NORMAL);
- }
- std::cout << "Simulation started.\n";
- }
- void stopKeyPressSimulation() {
- {
- std::lock_guard<std::mutex> lock(simulationMutex);
- if (!isRunning) {
- std::cout << "Simulation is not running.\n";
- return;
- }
- isRunning = false;
- }
- if (simulationThread.joinable()) {
- simulationThread.join();
- }
- std::cout << "Simulation stopped.\n";
- }
- int main() {
- const WORD key = VK_F11;
- const int delay = 1000;
- std::cout << "Key Press Simulator\n";
- std::cout << "1: Start Simulation\n";
- std::cout << "2: Stop Simulation\n";
- std::cout << "3: Exit\n";
- int choice;
- do {
- std::cout << "\nEnter your choice: ";
- std::cin >> choice;
- switch (choice) {
- case 1:
- startKeyPressSimulation(key, delay);
- break;
- case 2:
- stopKeyPressSimulation();
- break;
- case 3:
- stopKeyPressSimulation();
- std::cout << "Exiting program.\n";
- break;
- default:
- std::cout << "Invalid choice. Try again.\n";
- }
- } while (choice != 3);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement