I have some C++ code that I need to use for serial communication between PC and Arduino. The file "Serial.cpp" is including a file called "stdafx.h" that doesn't exist in the project or anywhere on my computer, which obviously causes an error.
Other than that, I also get other errors, such as C2065 'CSerial': undeclared identifier.
Here are the three files that are in the project:
Serial.h
#ifndef __SERIAL_H__
#define __SERIAL_H__
#pragma once
#include <Windows.h>
#include <memory.h>
#define FC_DTRDSR 0x01
#define FC_RTSCTS 0x02
#define FC_XONXOFF 0x04
#define ASCII_BEL 0x07
#define ASCII_BS 0x08
#define ASCII_LF 0x0A
#define ASCII_CR 0x0D
#define ASCII_XON 0x11
#define ASCII_XOFF 0x13
class CSerial
{
public:
CSerial();
~CSerial();
BOOL Open( int nPort = 2, int nBaud = 9600 );
BOOL Close( void );
int ReadData( void *, int );
int SendData( const char *, int );
int ReadDataWaiting( void );
BOOL IsOpened( void ){ return( m_bOpened ); }
protected:
BOOL WriteCommByte( unsigned char );
HANDLE m_hIDComDev;
OVERLAPPED m_OverlappedRead, m_OverlappedWrite;
bool m_bOpened;
};
#endif
Serial.cpp
// Serial.cpp
#include "stdafx.h"
#include "Serial.h"
CSerial::CSerial()
{
memset( &m_OverlappedRead, 0, sizeof( OVERLAPPED ) );
memset( &m_OverlappedWrite, 0, sizeof( OVERLAPPED ) );
m_hIDComDev = NULL;
m_bOpened = false;
}
CSerial::~CSerial()
{
Close();
}
BOOL CSerial::Open( int nPort, int nBaud )
{
if( m_bOpened ) return( TRUE );
wchar_t szPort[15];
wchar_t szComParams[50];
DCB dcb;
wsprintf( szPort, L"COM%d", nPort );
m_hIDComDev = CreateFile( szPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL );
if( m_hIDComDev == NULL ) return( FALSE );
memset( &m_OverlappedRead, 0, sizeof( OVERLAPPED ) );
memset( &m_OverlappedWrite, 0, sizeof( OVERLAPPED ) );
COMMTIMEOUTS CommTimeOuts;
CommTimeOuts.ReadIntervalTimeout = 0xFFFFFFFF;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
CommTimeOuts.ReadTotalTimeoutConstant = 0;
CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = 5000;
SetCommTimeouts( m_hIDComDev, &CommTimeOuts );
wsprintf( szComParams, L"COM%d:%d,n,8,1", nPort, nBaud );
m_OverlappedRead.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
m_OverlappedWrite.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
dcb.DCBlength = sizeof( DCB );
GetCommState( m_hIDComDev, &dcb );
dcb.BaudRate = nBaud;
dcb.ByteSize = 8;
unsigned char ucSet;
ucSet = (unsigned char) ( ( FC_RTSCTS & FC_DTRDSR ) != 0 );
ucSet = (unsigned char) ( ( FC_RTSCTS & FC_RTSCTS ) != 0 );
ucSet = (unsigned char) ( ( FC_RTSCTS & FC_XONXOFF ) != 0 );
if( !SetCommState( m_hIDComDev, &dcb ) ||
!SetupComm( m_hIDComDev, 10000, 10000 ) ||
m_OverlappedRead.hEvent == NULL ||
m_OverlappedWrite.hEvent == NULL ){
DWORD dwError = GetLastError();
if( m_OverlappedRead.hEvent != NULL ) CloseHandle( m_OverlappedRead.hEvent );
if( m_OverlappedWrite.hEvent != NULL ) CloseHandle( m_OverlappedWrite.hEvent );
CloseHandle( m_hIDComDev );
return( FALSE );
}
m_bOpened = TRUE;
return( m_bOpened );
}
BOOL CSerial::Close( void )
{
if( !m_bOpened || m_hIDComDev == NULL ) return( TRUE );
if( m_OverlappedRead.hEvent != NULL ) CloseHandle( m_OverlappedRead.hEvent );
if( m_OverlappedWrite.hEvent != NULL ) CloseHandle( m_OverlappedWrite.hEvent );
CloseHandle( m_hIDComDev );
m_bOpened = FALSE;
m_hIDComDev = NULL;
return( TRUE );
}
BOOL CSerial::WriteCommByte( unsigned char ucByte )
{
BOOL bWriteStat;
DWORD dwBytesWritten;
bWriteStat = WriteFile( m_hIDComDev, (LPSTR) &ucByte, 1, &dwBytesWritten, &m_OverlappedWrite );
if( !bWriteStat && ( GetLastError() == ERROR_IO_PENDING ) ){
if( WaitForSingleObject( m_OverlappedWrite.hEvent, 1000 ) ) dwBytesWritten = 0;
else{
GetOverlappedResult( m_hIDComDev, &m_OverlappedWrite, &dwBytesWritten, FALSE );
m_OverlappedWrite.Offset += dwBytesWritten;
}
}
return( TRUE );
}
int CSerial::SendData( const char *buffer, int size )
{
if( !m_bOpened || m_hIDComDev == NULL ) return( 0 );
DWORD dwBytesWritten = 0;
int i;
for( i=0; i<size; i++ ){
WriteCommByte( buffer[i] );
dwBytesWritten++;
}
return( (int) dwBytesWritten );
}
int CSerial::ReadDataWaiting( void )
{
if( !m_bOpened || m_hIDComDev == NULL ) return( 0 );
DWORD dwErrorFlags;
COMSTAT ComStat;
ClearCommError( m_hIDComDev, &dwErrorFlags, &ComStat );
return( (int) ComStat.cbInQue );
}
int CSerial::ReadData( void *buffer, int limit )
{
if( !m_bOpened || m_hIDComDev == NULL ) return( 0 );
BOOL bReadStatus;
DWORD dwBytesRead, dwErrorFlags;
COMSTAT ComStat;
ClearCommError( m_hIDComDev, &dwErrorFlags, &ComStat );
if( !ComStat.cbInQue ) return( 0 );
dwBytesRead = (DWORD) ComStat.cbInQue;
if( limit < (int) dwBytesRead ) dwBytesRead = (DWORD) limit;
bReadStatus = ReadFile( m_hIDComDev, buffer, dwBytesRead, &dwBytesRead, &m_OverlappedRead );
if( !bReadStatus ){
if( GetLastError() == ERROR_IO_PENDING ){
WaitForSingleObject( m_OverlappedRead.hEvent, 2000 );
return( (int) dwBytesRead );
}
return( 0 );
}
return( (int) dwBytesRead );
}
SerialExample.cpp
bool sendExample(int port, int baudRate)
{
char data[4];
CSerial* s = new CSerial();
if(!s->Open(port, baudRate))
{
std_out << _T("Could not open COM") << port << endl;
return false;
}
// Sending a string of 4 characters
data[0] = 0x31;
data[1] = 0x32;
data[2] = 0x33;
data[3] = 0x0D; // ASCII CR
s->SendData(data, 4);
s->Close();
delete s;
}
Does anyone know what I have to do?
stdafx.h is a precompiled header for Visual studio. so if you are not working in visual studio, you can just remove it and it should work just fine.
In regard to the compiler not recognizing the CSerial class -
I don't see where you include "CSerial.h" in SerialExample.cpp (i.e: #include "CSerial.h"), but if you do, this may also be a symptom of CSerial.cpp not compiling (less likely though)...
Hope this helps,
Lior
Related
I am following this tutorial for serial communication in windows (http://www.codeguru.com/cpp/i-n/network/serialcommunications/article.php/c2503/CSerial--A-C-Class-for-Serial-Communications.htm). I get the following errors, the code is fairly dated so I'm not sure if it is a version problem. I am using visual studio 2015 to run on Windows 10.
Serial.cpp:
// Serial.cpp
#include "stdafx.h"
CSerial::CSerial()
{
memset( &m_OverlappedRead, 0, sizeof( OVERLAPPED ) );
memset( &m_OverlappedWrite, 0, sizeof( OVERLAPPED ) );
m_hIDComDev = NULL;
m_bOpened = FALSE;
}
CSerial::~CSerial()
{
Close();
}
BOOL CSerial::Open( int nPort, int nBaud )
{
if( m_bOpened ) return( TRUE );
char szPort[15];
char szComParams[50];
DCB dcb;
wsprintf(szPort, "COM%d", nPort );
m_hIDComDev = CreateFile( szPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL );
if( m_hIDComDev == NULL ) return( FALSE );
memset( &m_OverlappedRead, 0, sizeof( OVERLAPPED ) );
memset( &m_OverlappedWrite, 0, sizeof( OVERLAPPED ) );
COMMTIMEOUTS CommTimeOuts;
CommTimeOuts.ReadIntervalTimeout = 0xFFFFFFFF;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
CommTimeOuts.ReadTotalTimeoutConstant = 0;
CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = 5000;
SetCommTimeouts( m_hIDComDev, &CommTimeOuts );
wsprintf( szComParams, "COM%d:%d,n,8,1", nPort, nBaud );
m_OverlappedRead.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
m_OverlappedWrite.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
dcb.DCBlength = sizeof( DCB );
GetCommState( m_hIDComDev, &dcb );
dcb.BaudRate = nBaud;
dcb.ByteSize = 8;
unsigned char ucSet;
ucSet = (unsigned char) ( ( FC_RTSCTS & FC_DTRDSR ) != 0 );
ucSet = (unsigned char) ( ( FC_RTSCTS & FC_RTSCTS ) != 0 );
ucSet = (unsigned char) ( ( FC_RTSCTS & FC_XONXOFF ) != 0 );
if( !SetCommState( m_hIDComDev, &dcb ) ||
!SetupComm( m_hIDComDev, 10000, 10000 ) ||
m_OverlappedRead.hEvent == NULL ||
m_OverlappedWrite.hEvent == NULL ){
DWORD dwError = GetLastError();
if( m_OverlappedRead.hEvent != NULL ) CloseHandle( m_OverlappedRead.hEvent );
if( m_OverlappedWrite.hEvent != NULL ) CloseHandle( m_OverlappedWrite.hEvent );
CloseHandle( m_hIDComDev );
return( FALSE );
}
m_bOpened = TRUE;
return( m_bOpened );
}
BOOL CSerial::Close( void )
{
if( !m_bOpened || m_hIDComDev == NULL ) return( TRUE );
if( m_OverlappedRead.hEvent != NULL ) CloseHandle( m_OverlappedRead.hEvent );
if( m_OverlappedWrite.hEvent != NULL ) CloseHandle( m_OverlappedWrite.hEvent );
CloseHandle( m_hIDComDev );
m_bOpened = FALSE;
m_hIDComDev = NULL;
return( TRUE );
}
BOOL CSerial::WriteCommByte( unsigned char ucByte )
{
BOOL bWriteStat;
DWORD dwBytesWritten;
bWriteStat = WriteFile( m_hIDComDev, (LPSTR) &ucByte, 1, &dwBytesWritten, &m_OverlappedWrite );
if( !bWriteStat && ( GetLastError() == ERROR_IO_PENDING ) ){
if( WaitForSingleObject( m_OverlappedWrite.hEvent, 1000 ) ) dwBytesWritten = 0;
else{
GetOverlappedResult( m_hIDComDev, &m_OverlappedWrite, &dwBytesWritten, FALSE );
m_OverlappedWrite.Offset += dwBytesWritten;
}
}
return( TRUE );
}
int CSerial::SendData( const char *buffer, int size )
{
if( !m_bOpened || m_hIDComDev == NULL ) return( 0 );
DWORD dwBytesWritten = 0;
int i;
for( i=0; i<size; i++ ){
WriteCommByte( buffer[i] );
dwBytesWritten++;
}
return( (int) dwBytesWritten );
}
int CSerial::ReadDataWaiting( void )
{
if( !m_bOpened || m_hIDComDev == NULL ) return( 0 );
DWORD dwErrorFlags;
COMSTAT ComStat;
ClearCommError( m_hIDComDev, &dwErrorFlags, &ComStat );
return( (int) ComStat.cbInQue );
}
int CSerial::ReadData( void *buffer, int limit )
{
if( !m_bOpened || m_hIDComDev == NULL ) return( 0 );
BOOL bReadStatus;
DWORD dwBytesRead, dwErrorFlags;
COMSTAT ComStat;
ClearCommError( m_hIDComDev, &dwErrorFlags, &ComStat );
if( !ComStat.cbInQue ) return( 0 );
dwBytesRead = (DWORD) ComStat.cbInQue;
if( limit < (int) dwBytesRead ) dwBytesRead = (DWORD) limit;
bReadStatus = ReadFile( m_hIDComDev, buffer, dwBytesRead, &dwBytesRead, &m_OverlappedRead );
if( !bReadStatus ){
if( GetLastError() == ERROR_IO_PENDING ){
WaitForSingleObject( m_OverlappedRead.hEvent, 2000 );
return( (int) dwBytesRead );
}
return( 0 );
}
return( (int) dwBytesRead );
}
Errors:
1>c:\..\consoleapplication2\serial.cpp(31): error C2664: 'int wsprintfW(LPWSTR,LPCWSTR,...)': cannot convert argument 1 from 'char [15]' to 'LPWSTR'
1>c:\..\consoleapplication2\serial.cpp(31): note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>c:\..\consoleapplication2\serial.cpp(32): error C2664: 'HANDLE CreateFileW(LPCWSTR,DWORD,DWORD,LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE)': cannot convert argument 1 from 'char [15]' to 'LPCWSTR'
1>c:\..\consoleapplication2\serial.cpp(32): note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>c:\..\consoleapplication2\serial.cpp(46): error C2664: 'int wsprintfW(LPWSTR,LPCWSTR,...)': cannot convert argument 1 from 'char [50]' to 'LPWSTR'
1>c:\..\consoleapplication2\serial.cpp(46): note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
Your error message:
error C2664: 'HANDLE CreateFileW(LPCWS
^ ~~~~
indicates you use UNICODE build (W indicates that CreateFile macro is defined with CreateFileW function), so you should use wide literal here (and in next wsprintf):
wsprintf(szPort, L"COM%d", nPort );
^ ~~~~~ !
and wchar_t array:
wchar_t szPort[15]; // or under winapi you would use WCHAR
wchar_t szComParams[50];
Properties-> Configuration Properties-> Advanced->Character Set-> Change from "Unicode Character Set" to "Multi-Byte Character Set"
Remember to remove the L later.
I have the following code. I'd like to add to this code a key BYTE[] and an IV BYTE[] too, to encrypt my data with. To do that i have to call CryptImportKey and CryptSetKeyParam.
So my questions are:
Where do i have to call theese two APIs? I think after CryptDeriveKey, and then use the output from CryptImportKey to encrypt my data. Am i right?
Can i somehow ensure that the result is correct encrypted? Should i make some other changes to make my code more secure?
#include <string>
#include <iostream>
using namespace std;
struct CryptStuff
{
HCRYPTPROV* hProv;
HCRYPTKEY* hKey;
HCRYPTHASH* hHash;
CryptStuff(HCRYPTPROV* hprov, HCRYPTKEY* hkey, HCRYPTHASH* hash) :
hProv(hprov), hKey(hkey), hHash(hash) {}
~CryptStuff()
{
if ( *hKey ) CryptDestroyKey( *hKey );
if ( *hHash ) CryptDestroyHash( *hHash );
if ( *hProv ) CryptReleaseContext( *hProv, 0 );
}
};
void EncryptData( TCHAR *lpszPassword, char *pbBuffer, DWORD *dwCount )
{
HCRYPTPROV hProv = 0;
HCRYPTKEY hKey = 0;
HCRYPTHASH hHash = 0;
// create an instance of CryptStuff. This will cleanup the data on return
CryptStuff cs(&hProv, &hKey, &hHash);
LPWSTR wszPassword = lpszPassword;
DWORD cbPassword = ( wcslen( wszPassword ) + 1 )*sizeof( WCHAR );
if ( !CryptAcquireContext( &hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES,
CRYPT_VERIFYCONTEXT ) )
{
return;
}
if ( !CryptCreateHash( hProv, CALG_SHA_256, 0, 0, &hHash ) )
{
return;
}
if ( !CryptHashData( hHash, ( PBYTE )wszPassword, cbPassword, 0 ) )
{
return;
}
if ( !CryptDeriveKey( hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey ) )
{
return;
}
DWORD size = ( DWORD )strlen( pbBuffer ) / sizeof( char );
cout << "\nLength of string = " << size;
if ( !CryptEncrypt( hKey, 0, TRUE, 0, ( LPBYTE )pbBuffer, &size, BLOCK_SIZE ) )
{
return;
}
cout << "\nEncrypted bytes = " << size;
cout << "\nEncrypted text = ";
cout.write(pbBuffer, size);
if ( !CryptDecrypt( hKey, 0, TRUE, 0, ( LPBYTE )pbBuffer, &size ) )
{
return;
}
cout << "\nDecrypted bytes = " << size;
cout << "\nDecrypted text = ";
cout.write(pbBuffer, size);
}
Thanks in advance!
We have an application that has 3 processes as shown in the image below.
What I wanted to do is to terminate these processes. After reading a few tutorials, I was able to collate these codes. However, it's not working properly. The output is shown after the code.
HANDLE hProcessSnap;
PROCESSENTRY32 pe32;
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
pe32.dwSize = sizeof( PROCESSENTRY32 );
std::string message = "";
int processCounter = 0;
while( Process32Next( hProcessSnap, &pe32 ) ) {
char ch[260];
char DefChar = ' ';
WideCharToMultiByte(CP_ACP,0,pe32.szExeFile,-1, ch,260,&DefChar, NULL);
//A std:string using the char* constructor.
std::string process(ch);
if( process == "bridge.exe" ) {
std::wstring stemp = std::wstring(process.begin(), process.end());
LPCWSTR sw = stemp.c_str();
HWND windowHandle = FindWindowW( NULL, sw );
DWORD* dwProcessId = new DWORD;
GetWindowThreadProcessId( windowHandle, dwProcessId );
message.append( process );
message.append( "-" );
std::ostringstream converter;
converter << *dwProcessId;
message.append( converter.str() );
message.append( "-" );
DWORD dwDesiredAccess = PROCESS_TERMINATE;
BOOL bInheritHandle = FALSE;
HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, *dwProcessId);
if( hProcess == NULL ) {
BOOL result = TerminateProcess(hProcess, 0);
message.append( "NULL" );
}
message.append( "\n" );
CloseHandle(hProcess);
}
}
This is the output:
bridge.exe-4597928-NULL
bridge.exe-4597568-NULL
bridge.exe-4587524-NULL
hProcess returns NULL. What did I miss? Thanks.
I am trying to create a program that functions similar to a task manager along with many other capabilities. Currently, I am having trouble finding all the top-level windows with my current enumeration function. For some reason, it enumerates and fills out the HWND for some applications properly ( e.g. Google Chrome, Command Prompt, Code::Blocks ), but not for some games( e.g. Roblox ( only one I tested ) ). I tried to see if maybe FindWindow() would fail too, but it worked fine in that context. Which means that EnumWindows() should obviously find it, but apparently I either did something wrong or I read something wrong in the documentation. I really don't want to have to use FindWindow( ) when I probably won't know the title of most windows anyways.
Enumeration function :
BOOL CALLBACK FindWindows( HWND handle, LPARAM option )
{
DWORD window_process_id = 0;
GetWindowThreadProcessId( handle, &window_process_id );
process_list * p1 = NULL;
switch ( option )
{
case FIND_WINDOW_HANDLE :
if ( IsWindowEnabled( handle ) )
for ( p1 = head_copy; p1; p1 = p1->next )
if ( p1->pid == window_process_id )
p1->window_handle = handle;
break;
default :
SetLastError( ERROR_INVALID_PARAMETER );
return 0;
break;
}
return TRUE;
}
Full source :
/* Preprocessor directives */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#define TARGET_PROCESS "chrome.exe"
/* Structures */
typedef struct process_list
{
char * process_name;
DWORD pid;
HANDLE process_handle;
HWND window_handle;
int process_name_sz;
struct process_list * next;
} process_list;
typedef struct drawing_data
{
RECT window_pos;
} drawing_data;
/* Enums ( Global integer constants ) */
enum
{
FIND_WINDOW_HANDLE
};
enum
{
TIMER_START,
TIMER_STOP,
TIMER_GETDIFF
};
typedef struct t_timer
{
clock_t start_time;
clock_t end_time;
} t_timer;
/* Global variables */
process_list * head_copy = NULL;
/* ***************************************************************** */
/* Time functions */
clock_t timer( int command, t_timer * timer1 )
{
switch ( command )
{
case TIMER_START :
timer1->start_time = clock( );
break;
case TIMER_STOP :
timer1->end_time = clock( );
break;
case TIMER_GETDIFF :
return ( ( timer1->end_time - timer1->start_time ) / ( CLOCKS_PER_SEC / 1000 ));
break;
default : break;
}
return -1;
}
/* ***************************************************************** */
/* Windows error functions */
void show_error( char * user_string, BOOL exit )
{
char buffer[BUFSIZ] = { 0 };
DWORD error_code = GetLastError( );
FormatMessage
(
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) buffer,
BUFSIZ,
NULL
);
printf( "%s : %s", user_string, buffer );
if ( exit ) ExitProcess( error_code );
return;
}
/* ***************************************************************** */
void win_error( char * message, BOOL exit )
{
char buffer[BUFSIZ] = { 0 };
DWORD error_code = GetLastError( );
FormatMessage
(
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) buffer,
BUFSIZ,
NULL
);
MessageBox(NULL, buffer, "Error from System :", MB_ICONWARNING | MB_OK );
if ( exit ) ExitProcess( error_code );
return;
}
/* ***************************************************************** */
/* Linked list functions */
process_list * create( )
{
process_list * temp = NULL;
if ( !( temp = malloc( sizeof( process_list ) ) ) )
{
perror("Malloc");
exit( 1 );
}
return temp;
}
/* ***************************************************************** */
process_list * add( process_list * head, HANDLE process_handle, PROCESSENTRY32 * process_structure )
{
process_list * temp = NULL;
if ( !head )
{
head = create( );
head->pid = process_structure->th32ParentProcessID;
head->process_handle = process_handle;
head->process_name_sz = strlen( process_structure->szExeFile ) + 1;
head->process_name = malloc( head->process_name_sz );
if ( !head->process_name )
{
perror( "Malloc" );
exit( 1 );
}
strcpy( head->process_name, process_structure->szExeFile );
head->next = NULL;
} else
{
temp = create( );
temp->next = head;
head = temp;
head->pid = process_structure->th32ParentProcessID;
head->process_handle = process_handle;
head->process_name_sz = strlen( process_structure->szExeFile ) + 1;
head->process_name = malloc( head->process_name_sz );
if ( !head->process_name )
{
perror( "Malloc" );
exit( 1 );
}
strcpy( head->process_name, process_structure->szExeFile );
}
return head;
}
/* ***************************************************************** */
void print_list( process_list * head )
{
process_list * p1 = NULL;
for ( p1 = head; p1; p1 = p1->next )
{
printf(
"-------------------------------------------------\n"
"node.process_name\t=\t%s\n"
"node.process_id\t\t=\t%d\n"
"\nCan terminate process : %s\n\n"
"node.window_handle\t=\t0x%p\n"
"node.next\t\t=\t%s\n",
p1->process_name,
( int )p1->pid,
p1->process_handle == INVALID_HANDLE_VALUE ? "NO" : "YES",
( void * )p1->window_handle,
p1->next ? "(node address)\n" : "NULL"
);
}
}
/* ***************************************************************** */
void print_node( process_list * node )
{
printf(
"node.process_name\t=\t%s\n"
"node.process_id\t\t=\t%d\n"
"\nCan terminate process : %s\n\n"
"node.window_handle\t=\t0x%p\n"
"node.next\t\t=\t%s\n",
node->process_name,
( int )node->pid,
node->process_handle == INVALID_HANDLE_VALUE ? "NO" : "YES",
( void * )node->window_handle,
node->next ? "(node address)\n" : "NULL"
);
return;
}
/* ***************************************************************** */
process_list * delete( process_list * head, process_list * node )
{
process_list * p1 = head;
process_list * p2 = NULL;
if ( !p1 )
return NULL;
else if ( p1 == node )
{
if ( !p1->next )
{
free( p1->process_name );
if ( p1->process_handle != INVALID_HANDLE_VALUE )
CloseHandle( p1->process_handle );
if ( p1->window_handle )
CloseHandle( p1->window_handle );
free( p1 );
}
else
{
free( p1->process_name );
if ( p1->process_handle != INVALID_HANDLE_VALUE )
CloseHandle( p1->process_handle );
if ( p1->window_handle )
CloseHandle( p1->window_handle );
p2 = head->next;
free( p1 );
return p2;
}
return NULL;
}
for ( ; p1 && p1 != node; p2 = p1, p1 = p1->next );
if ( !p1 )
return NULL;
else
{
free( p1->process_name );
if ( p1->process_handle != INVALID_HANDLE_VALUE )
CloseHandle( p1->process_handle );
if ( p1->window_handle )
CloseHandle( p1->window_handle );
p2->next = p1->next;
free( p1 );
}
return head;
}
/* ***************************************************************** */
void free_list( process_list * head )
{
process_list * p1 = head;
process_list * p2 = NULL;
while ( p1 )
{
free( p1->process_name );
if ( p1->process_handle != INVALID_HANDLE_VALUE )
CloseHandle( p1->process_handle );
if ( p1->window_handle )
CloseHandle( p1->window_handle );
p2 = p1;
p1 = p1->next;
free( p2 );
}
return;
}
/* ***************************************************************** */
process_list * find_process_and_copy_node( process_list * head, const char * process_name )
{
BOOL is_match = FALSE;
process_list * p1 = NULL;
process_list * new_node = NULL;
for ( p1 = head; p1; p1 = p1->next )
{
if ( !strcmp( p1->process_name, process_name ) )
{
is_match = TRUE;
break;
}
}
if ( is_match )
{
new_node = create( );
new_node->pid = p1->pid;
new_node->process_handle = p1->process_handle;
if ( !( new_node->process_name = malloc( p1->process_name_sz ) ) )
{
perror( "Malloc" );
free( new_node );
free_list( head );
exit( 1 );
}
new_node->process_name = strcpy( new_node->process_name, p1->process_name );
new_node->process_name_sz = p1->process_name_sz;
new_node->window_handle = p1->window_handle;
new_node->next = NULL;
return new_node;
}
else return NULL;
}
/* ***************************************************************** */
/* WinAPI functions */
BOOL CALLBACK FindWindows( HWND handle, LPARAM option )
{
DWORD window_process_id = 0;
GetWindowThreadProcessId( handle, &window_process_id );
process_list * p1 = NULL;
switch ( option )
{
case FIND_WINDOW_HANDLE :
if ( IsWindowEnabled( handle ) )
for ( p1 = head_copy; p1; p1 = p1->next )
if ( p1->pid == window_process_id )
p1->window_handle = handle;
break;
default :
SetLastError( ERROR_INVALID_PARAMETER );
return 0;
break;
}
return TRUE;
}
/* ***************************************************************** */
process_list * get_process_list( process_list * head )
{
HANDLE h_process_snap;
HANDLE h_process;
PROCESSENTRY32 process_structure;
h_process_snap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( h_process_snap == INVALID_HANDLE_VALUE )
{
show_error( "CreateToolhelp32Snapshot", FALSE );
return NULL;
}
process_structure.dwSize = sizeof( PROCESSENTRY32 );
if( !Process32First( h_process_snap, &process_structure ) )
{
show_error( "Process32First", FALSE );
CloseHandle( h_process_snap );
return NULL;
}
do
{
h_process = OpenProcess( PROCESS_TERMINATE, FALSE, process_structure.th32ProcessID );
if ( h_process )
head = add( head, h_process, &process_structure );
else
head = add( head, INVALID_HANDLE_VALUE, &process_structure );
} while( Process32Next( h_process_snap, &process_structure ) );
CloseHandle( h_process_snap );
return head;
}
/* ***************************************************************** */
process_list * find_process( const char * process_name )
{
process_list * head = NULL;
process_list * target_process = NULL;
if ( !( head = get_process_list( head ) ) )
exit( 1 );
head_copy = head;
if ( !EnumWindows( FindWindows, FIND_WINDOW_HANDLE ) )
win_error( "EnumWindows", FALSE );
target_process = find_process_and_copy_node( head, TARGET_PROCESS );
free_list( head );
return target_process;
}
/* ***************************************************************** */
int main( )
{
t_timer program_run_time;
memset( &program_run_time, 0, sizeof( t_timer ) );
timer( TIMER_START, &program_run_time );
process_list * target_process = NULL;
printf("Searching for target process...\n");
while ( !( target_process = find_process( TARGET_PROCESS ) ) )
Sleep( 100 );
printf("Found!\n\n");
print_node( target_process );
timer( TIMER_STOP, &program_run_time );
printf( "\n\n\t--\tProgram run time : %d milliseconds\t--\t\n\n", ( int )timer( TIMER_GETDIFF, &program_run_time ) );
free( target_process->process_name );
free( target_process );
return 0;
}
If you can see it in Spy++, you should be able to get at it with EnumWindows.
But if your query is ROBLOX-specific and all you want is the window handle, you can do
foreach (Process p in Process.GetProcesses())
{
if (p.MainWindowTitle == "Roblox - [Place1]")
{
rbxProc = p;
Console.WriteLine("FOUND ROBLOX Process");
}
}
and then you can get the main handle like this:
rbxProc.MainWindowHandle
Can I push a binary on a remote host windows using WINRM.
If not is there any other mechanism which allows me to push a binary on remote host.
I think I found a solution.
#include <windows.h>
#include <tchar.h>
#define SIZEOF_BUFFER 0x100
// Remote Parameters
LPCTSTR lpszMachine = NULL;
LPCTSTR lpszPassword = NULL;
LPCTSTR lpszUser = NULL;
LPCTSTR lpszDomain = NULL;
LPCTSTR lpszCommandExe = NULL;
LPCTSTR lpszLocalIP = _T("\\\\127.0.0.1");
char szThisMachine[SIZEOF_BUFFER] = "";
char szPassword[SIZEOF_BUFFER] = "";
LPCTSTR GetParamValue( LPCTSTR lpszParam )
{
DWORD dwParamLength = _tcslen( lpszParam );
for ( int i = 1; i < __argc; i++ )
if ( __targv[i][0] == _T('\\') || __targv[i][0] == _T('.'))
continue;
else
if ( __targv[i][0] == _T('/') || __targv[i][0] == _T('-') )
{
if ( _tcsnicmp( __targv[i] + 1, lpszParam, dwParamLength ) == 0 )
return __targv[i] + dwParamLength + 1;
}
else
return NULL;
return NULL;
}
LPCTSTR GetNthParameter( DWORD n, DWORD& argvIndex )
{
DWORD index = 0;
for( int i = 1; i < __argc; i++ )
{
if ( __targv[i][0] != _T('/') && __targv[i][0] != _T('-') )
index++;
if ( index == n )
{
argvIndex = i;
return __targv[i];
}
}
return NULL;
}
BOOL SetConnectionCredentials()
{
lpszPassword = GetParamValue( _T("pwd:") );
lpszUser = GetParamValue( _T("user:") );
return TRUE;
}
LPCTSTR GetRemoteMachineName()
{
DWORD dwIndex = 0;
LPCTSTR lpszMachine = GetNthParameter( 1, dwIndex );
if ( lpszMachine == NULL )
// return NULL;
return lpszLocalIP;
if ( _tcsnicmp( lpszMachine, _T(" "), 2 ) == 0 )
return lpszLocalIP;
if ( _tcsnicmp( lpszMachine, _T("\\\\"), 2 ) == 0 )
return lpszMachine;
// If a dot is entered we take it as localhost
if ( _tcsnicmp( lpszMachine, _T("."), 2 ) == 0 )
return lpszLocalIP;
return NULL;
}
// Establish Connection to Remote Machine
BOOL EstablishConnection( LPCTSTR lpszRemote, LPCTSTR lpszResource, BOOL bEstablish )
{
TCHAR szRemoteResource[_MAX_PATH];
DWORD rc;
_stprintf( szRemoteResource, _T("%s\\%s"), lpszRemote, lpszResource );
NETRESOURCE nr;
nr.dwType = RESOURCETYPE_ANY;
nr.lpLocalName = NULL;
nr.lpRemoteName = (LPTSTR)&szRemoteResource;
nr.lpProvider = NULL;
//Establish connection (using username/pwd)
rc = WNetAddConnection2( &nr, lpszPassword, lpszUser, FALSE );
if ( rc == NO_ERROR )
return TRUE; // indicate success
return FALSE;
}
BOOL CopyBinaryToRemoteSystem()
{
TCHAR drive[_MAX_DRIVE];
TCHAR dir[_MAX_DIR];
TCHAR fname[_MAX_FNAME];
TCHAR ext[_MAX_EXT];
TCHAR szRemoteResource[_MAX_PATH];
// Gets the file name and extension
_tsplitpath( lpszCommandExe, drive, dir, fname, ext );
_stprintf( szRemoteResource, _T("%s\\ADMIN$\\System32\\%s%s"), lpszMachine, fname, ext );
// Copy the Command's exe file to \\remote\ADMIN$\System32
return CopyFile( lpszCommandExe, szRemoteResource, FALSE );
}
int _tmain( DWORD, TCHAR**, TCHAR** )
{
int rc = 0;
DWORD dwIndex = 0;
lpszMachine = GetRemoteMachineName();
lpszCommandExe = GetNthParameter( 2, dwIndex );
SetConnectionCredentials();
if ( !EstablishConnection( lpszMachine, _T("ADMIN$"), TRUE ) )
{
rc = -2;
}
if ( !CopyBinaryToRemoteSystem())
{
}
return 0;
}