我是C ++的初学者,我遇到了问题。如果我做一个或两个线程,那么程序运行正常。如果我做了超过2个线程,那么当我按住“q”(GetAsyncKeyState(81))时它会崩溃。另外,有没有办法加快这个过程?提前谢谢。
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <string>
#include <thread>
#include <vector>
using namespace std;
/* Globals */
int ScreenX = 400;
int ScreenY = 400;
int CenterX = 686;
int CenterY = 410;
BYTE* ScreenData = 0;
HDC hScreen;
HBITMAP hBitmap;
HDC hdcMem;
HGDIOBJ hOld;
BITMAPINFOHEADER bmi;
void ScreenCap()
{
hScreen = GetDC(NULL);
hBitmap = CreateCompatibleBitmap(hScreen, ScreenX, ScreenY);
hdcMem = CreateCompatibleDC (hScreen);
hOld = SelectObject(hdcMem, hBitmap);
BitBlt(hdcMem, 0, 0, ScreenX, ScreenY, hScreen, CenterX - 150, CenterY - 150, SRCCOPY);
SelectObject(hdcMem, hOld);
bmi = {0};
bmi.biSize = sizeof(BITMAPINFOHEADER);
bmi.biPlanes = 1;
bmi.biBitCount = 32;
bmi.biWidth = ScreenX;
bmi.biHeight = -ScreenY;
bmi.biCompression = BI_RGB;
bmi.biSizeImage = 0;// 3 * ScreenX * ScreenY;
if(ScreenData)
free(ScreenData);
ScreenData = (BYTE*)malloc(4 * ScreenX * ScreenY);
GetDIBits(hdcMem, hBitmap, 0, ScreenY, ScreenData, (BITMAPINFO*)&bmi, DIB_RGB_COLORS);
SelectObject(hdcMem, hBitmap);
DeleteObject(hOld);
ReleaseDC(GetDesktopWindow(),hScreen);
DeleteDC(hdcMem);
}
inline int PosB(int x, int y)
{
return ScreenData[4*((y*ScreenX)+x)];
}
inline int PosG(int x, int y)
{
return ScreenData[4*((y*ScreenX)+x)+1];
}
inline int PosR(int x, int y)
{
return ScreenData[4*((y*ScreenX)+x)+2];
}
bool ButtonPress(int Key)
{
bool button_pressed = false;
while(GetAsyncKeyState(Key))
button_pressed = true;
return button_pressed;
}
struct Foo {};
void ThreadT(const Foo& f)
{
while (true)
{
Sleep(16);
if (GetAsyncKeyState(81))
{
ScreenCap();
int tobreak = 0;
//POINT Highest;
for (int x = 0; x < ScreenX; x++)
{
if (tobreak == 1)
break;
for (int y = 0; y < ScreenY; y++)
{
if (tobreak == 1)
break;
int Red = PosR(x, y);
int Green = PosG(x, y);
int Blue = PosB(x, y);
if (Blue < 100 && Red < 100 && Green > 200)
{
x = (x + (CenterX - 150));
y = (y + (CenterY - 150));
//cout << ">:D ";
/*POINT pos;
GetCursorPos(&pos);
int DX = x - CenterX;
int DY = y - CenterY;
//int DX = pos.x - x;
//int DY = pos.y - y;
//SetCursorPos(x + DX, y + DY);
SetCursorPos(pos.x + DX, pos.y + DY);*/
//SetCursorPos(x, y);
/*POINT newPos;
Sleep(1000);
GetCursorPos(&newPos);
cout << x << ", " << y << " / " << newPos.x << ", " << newPos.y << endl;*/
//cout << pos.x + DX << ", " << pos.y + DY << endl;
//cout << x << ", " << y << endl;
SetCursorPos(x, y);
tobreak = 1;
}
}
}
}
}
}
int main()
{
vector<thread> threads;
for (int i = 0; i < 1; i++)
{
threads.push_back(thread(ThreadT, Foo()));
}
// do some other stuff
// loop again to join the threads
for (auto& t : threads)
t.join();
system("PAUSE");
return 0;
}