c++,每次鼠标点击执行1个循环

C++, execute 1 loop per mouse click?

本文关键字:执行 1个 循环 鼠标 c++      更新时间:2023-10-16

我是c++的新手,我想知道是否有人可以帮助我。在DOS窗口中单击鼠标左键打印"hello world"的正确循环结构是什么?

我做了一些搜索,我到达了类似

的东西
if ((GetKeyState(VK_LBUTTON) & 0x80) != 0) 
{
   printf("Hello World!n"); 
}

或者一个事件会更好吗?

"hello world"将是一个从网络摄像头捕获图像的代码。最初的教程代码有一个while循环(总是为真),最终流媒体视频。我的目标是通过鼠标点击捕捉1帧。我试图得到一个简化的版本与这个你好世界的东西工作。

如果你现在这样做,你可能得不到想要的结果。把鼠标想象成在一个单独的线程上运行。当调用代码行查看鼠标是否被按下时,结果可能为false,即使用户在该特定帧中按下了鼠标。

some code            <-- mouse button pressed by user
some code            <-- mouse button released by user
some code
your mouse check     <-- mouse button check is false (undesired result)
some code
some code

事件解决了这个问题,因为按下和释放中断存储在缓冲区中(由操作系统)。这就消除了时间问题。我不确定您使用的是什么库,但如果是sdl或sfml之类的库,那么您可以使用事件循环来决定要做什么。

事件循环(在"大型游戏循环"中)应该是这样的:

while(there's still events){
    if(mouse press event){
        do what you want on mouse press
    }
}

因为在任意两帧之间可能有多个鼠标按下事件,我将创建一个bool mouseWasPressed默认值为false,并在所需事件发生时将其设置为true。

bool mouseWasPressed = false;
while(there's still events){
    if(mouse press event){
        if(!mouseWasPressed){
            mouseWasPressed = true;
            capture frame for video
        }
    }
}

这种方式可以消除每帧多个鼠标按下事件(即使它们不太可能)。当我说鼠标按下事件时,我假设您正在过滤特定的鼠标按钮

如果你想为每次点击(你的标题暗示…)重复捕获,你将不得不循环。然后它将是一个活动循环(在伪代码中)

while true {
    if _mouse_click_ {
        // your stuff
    }
}

使用事件循环总是更好的(我假设你是在Windows上),因为操作系统只在事件发生时才给你的程序时间片,而不是让你的程序浪费时间片来测试发生…并可能饿死其他应用程序…

对于控制台窗口中的鼠标处理,使用ReadConsoleInput并检查事件Event.MouseEvent.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED是否发生。然后粘贴你的摄像头代码在那里。

#include <iostream>
#include <stdlib.h>
#include <windows.h>
using namespace std;

int main()
{ 
    cout<<"click anywhere in console window to write - hello world -nnnnnnnnnnnnn"
    "Press Ctrl+C to Exit"; 
        HANDLE hout= GetStdHandle(STD_OUTPUT_HANDLE);
        HANDLE hin = GetStdHandle(STD_INPUT_HANDLE); 
        INPUT_RECORD InputRecord; 
        DWORD Events; 
        COORD coord;
        CONSOLE_CURSOR_INFO cci;
        cci.dwSize = 25;
        cci.bVisible = FALSE;
        SetConsoleCursorInfo(hout, &cci); 
        SetConsoleMode(hin, ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT); 

    while(1)
    { 
        ReadConsoleInput(hin, &InputRecord, 1, &Events); 
        if(InputRecord.EventType == MOUSE_EVENT) 
        {
            if(InputRecord.Event.MouseEvent.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) 
            { 
                coord.X = InputRecord.Event.MouseEvent.dwMousePosition.X; 
                coord.Y = InputRecord.Event.MouseEvent.dwMousePosition.Y; 
                SetConsoleCursorPosition(hout,coord);
                SetConsoleTextAttribute(hout,rand() %7+9);
                cout<<"Hello world" ; 
            } 
        }
        FlushConsoleInputBuffer(hin);
    }
    return 0;
}