gpt4 book ai didi

c++ - 计算鼠标点击次数 C

转载 作者:太空宇宙 更新时间:2023-11-04 07:15:33 28 4
gpt4 key购买 nike

我有一个 C 代码,用于检查是否按下了鼠标左键。它工作正常,但我想用它来计算按钮被点击的次数,并在按钮被随机点击时调用一个函数。

这是代码:

LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
int count = 0;
MOUSEHOOKSTRUCT * pMouseStruct = (MOUSEHOOKSTRUCT *)lParam;
if (pMouseStruct != NULL){
if (wParam == WM_LBUTTONDOWN)
{
count++;
printf("%d",count);
if (count==finalNum){ // user clicked random times the mouse so we launch the final function
printf("\ndone!\n");
final();

}
printf("clicked");
}
printf("Mouse position X = %d Mouse Position Y = %d\n", pMouseStruct->pt.x, pMouseStruct->pt.y);
}
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}

DWORD WINAPI MyMouseLogger(LPVOID lpParm)
{
HINSTANCE hInstance = GetModuleHandle(NULL);
// here I put WH_MOUSE instead of WH_MOUSE_LL
hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, mouseProc, hInstance, NULL);
MSG message;

while (GetMessage(&message, NULL, 0, 0)) {
TranslateMessage(&message);
DispatchMessage(&message);
}

UnhookWindowsHookEx(hMouseHook);
return 0;
}

void custom_delay(){

}

int main(int argc, char *argv[])
{
int count = 0;
HANDLE hThread;
DWORD dwThread;
//////Generate random number to call a function after rand() number of clicks
srand(time(NULL)); // Seed the time
int finalNum = rand() % (150 - 50) + 50; // Generate the number, assign to variable.
////////////////////////////////////////////////////////////////////////////

printf("%d", finalNum);
hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)MyMouseLogger, (LPVOID)argv[0], NULL, &dwThread);
if (hThread)
return WaitForSingleObject(hThread, INFINITE);
else
return 1;
}
}

问题是每次发生鼠标事件时计数变量都会重置为 0,因此我无法跟踪用户点击鼠标的次数。

另一个问题是我想生成 50 到 150 之间的随机次数来调用 final() 函数。我如何发送该随机数作为参数?

谢谢你的帮助!

最佳答案

由于您在函数中声明了 count,它在函数被调用时分配,并在函数返回时自动释放,如果您希望 count 持续更长时间,您可以将其设为全局(声明它在函数之外)。

或者您在count 的声明中使用static 关键字,即static int count = 0。当一个变量被声明为 static 时,它被分配给整个程序的长度。这样当函数返回 count 时不会被取消分配。这是有关静态的更多信息-
What does static mean in ANSI-C
http://en.wikipedia.org/wiki/Static_variable

现在对于问题的下一部分,您可以使用 rand 函数在 C 语言中生成一个伪随机数。函数 rand 返回一个从 0RAND_MAX 的整数,它是标准库定义的常量。您可以在此处阅读有关 rand 的更多信息 - http://www.cplusplus.com/reference/cstdlib/rand/

此外,如果您想存储一些随机数并能够从 mouseProc 访问它,您可以给它全局范围,但请注意,将所有变量都设置为一个好习惯并不总是全局的。 http://en.wikipedia.org/wiki/Scope_(computer_science)

关于c++ - 计算鼠标点击次数 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25112698/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com