简体   繁体   English

如何保持程序运行

[英]How to keep program running

I want my code to keep on running without exiting.我希望我的代码在不退出的情况下继续运行。 Is there a way to do this, or do I have to use an infinite loop to keep it running.有没有办法做到这一点,或者我必须使用无限循环来保持它运行。

#include <iostream>
#include <windows.h>
#include <chrono>
#include <thread>
#include <math.h>
#include <random>
#include <fstream>
using namespace std;

int main()
{
    POINT coord;
    GetCursorPos(&coord);
    fstream file;
    file.open("example.txt", ios::out | ios::in);


    // Reding from file
    

    //closing the file
    int xCoord;
    int yCoord;
    
    GetCursorPos(&coord);
    
    if (MOUSEEVENTF_LEFTDOWN) {
        cout << "Coords: " << coord.x << " , " << coord.y << "\n";
            xCoord = coord.x;
            yCoord = coord.y;
            file << xCoord << "," << yCoord << endl;
    }
   

   

    return 0;
}

Basically, the idea is to log every left click a user has done and put them in a text file, but it just ends after getting one iteration.基本上,这个想法是记录用户所做的每一次左键单击并将它们放在一个文本文件中,但它只会在一次迭代后结束。 Is there a way for it to take more than 1 iteration?有没有办法让它进行超过 1 次迭代? I've tried using a for infinite loop, but it just floods the whole file with the same coordinates.我试过使用 for 无限循环,但它只是用相同的坐标淹没整个文件。

I would use while(!GetAsyncKeystate(VK_END)) to keep the code running however for this to work as intended you want to also change if(MOUSEEVENTF_LEFTDOWN) to if (GetAsyncKeyState(VK_LBUTTON )) {我会使用while(!GetAsyncKeystate(VK_END))来保持代码运行,但是要使其按预期工作,您还希望将if(MOUSEEVENTF_LEFTDOWN)更改为if (GetAsyncKeyState(VK_LBUTTON )) {

So your code would now look like所以你的代码现在看起来像

    int xCoord;
    int yCoord;
    while (!GetAsyncKeyState(VK_END)) {
    GetCursorPos(&coord);
 

        if (GetAsyncKeyState(VK_LBUTTON ) & 1) {
            cout << "Coords: " << coord.x << " , " << coord.y << "\n";
            xCoord = coord.x;
            yCoord = coord.y;
            file << xCoord << "," << yCoord << endl;
        }
    }
}

When you press the END key on your keyboard your program will stop:3当您按下键盘上的 END 键时,您的程序将停止:3

The problem here is that MOUSEEVENTF_LEFTDOWN is a constant value.这里的问题是MOUSEEVENTF_LEFTDOWN是一个常量值。 This documentation says the value is 0x0002 .文档说该值为0x0002

This means that:这意味着:

if (MOUSEEVENTF_LEFTDOWN)  // this is always true.
                          

So if you add a loop this if condition is always true so it will record a value every iteration of the loop.因此,如果您添加一个循环,则此 if 条件始终为真,因此它将在循环的每次迭代中记录一个值。 You need to find a function that returns the state of the mouse button.您需要找到返回鼠标按钮的 state 的 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM