c++,每次鼠标点击执行1个循环
C++, execute 1 loop per mouse click?
我是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;
}
- 按 Tab 单步执行两个控制组
- 如何在 Qt5 中执行多个 QProcess
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 在 Radeon 卡上并行执行多个 OpenCL 内核
- 在 MySQL 连接器C++ API 中使用一个函数调用执行多个查询的正确方法是什么?
- 如何在R和C 中分别执行两个矩阵的矩阵产物
- 如何执行两个函数参数具有相同的模板类型
- C++中更快地执行两个程序的可能解释(使用 Python 比较)?
- 使file执行多个程序(C/C )
- 执行三个嵌套for循环的最快方法是什么
- 如何使用'#define';定义一个宏来执行多个方法
- 如何在 [action-if-true] 中执行多个操作
- 如何让谷歌测试在QtCreator中执行多个测试文件
- 如何在 c++ 中设置 ODBC 连接以执行多个查询 (SQLExecDirect)
- 如何在安卓中执行多个CMakeLists.txt文件
- 我可以使用相同的qsqlquery变量执行多个语句
- 壳执行多个文件
- 此合并排序算法执行多少个比较
- 如何在C 中的用户提交变量列表中执行多个操作
- 正确重复使用ADODB命令对象执行多个查询