I have mistakes in my code. My printer which name is "XP-58" does not print text from C++ program.
But when I run print from notepat, it works correctrly.
My C++ code
int _tmain(int argc, _TCHAR* argv[])
{
LPTSTR printerName = (LPTSTR)_T("XP-58");
CString str = "la-la-la";
LPBYTE pByte = new BYTE[str.GetLength() + 1];
memcpy(pByte, (VOID*)LPCTSTR(str), str.GetLength());
DWORD count = 7;
BOOL result = RawDataToPrinter(printerName, pByte, count);
std::cout << result << std::endl;
system("pause");
return 0;
}
I using function from here https://msdn.microsoft.com/en-us/library/windows/desktop/dd162959(v=vs.85).aspx
As you can see I have result after program end "std::cout << result << std::endl;" and result always shows "1".
Which is the problem?
May be I need set specify port for printer? My printer connected to USB002 port.
And when I start printing from notepad I see this port in "Print queue manager", but when task added from my program I don't see any port in manager.
Please help)
Full code
#include "stdafx.h"
#include <Windows.h>
#include <Winspool.h>
#include <CommDlg.h>
#include <math.h>
#include <atlstr.h>
#include <iostream>
BOOL RawDataToPrinter(LPTSTR szPrinterName, LPBYTE lpData, DWORD dwCount)
{
BOOL bStatus = FALSE;
HANDLE hPrinter = NULL;
DOC_INFO_1 DocInfo;
DWORD dwJob = 0L;
DWORD dwBytesWritten = 0L;
// Open a handle to the printer.
bStatus = OpenPrinter( szPrinterName, &hPrinter, NULL );
if (bStatus) {
// Fill in the structure with info about this "document."
DocInfo.pDocName = (LPTSTR)_T("chargebox barcode check");
DocInfo.pOutputFile = NULL;
DocInfo.pDatatype = (LPTSTR)_T("RAW");
// Inform the spooler the document is beginning.
dwJob = StartDocPrinter( hPrinter, 1, (LPBYTE)&DocInfo );
if (dwJob > 0) {
// Start a page.
bStatus = StartPagePrinter( hPrinter );
if (bStatus) {
// Send the data to the printer.
bStatus = WritePrinter( hPrinter, lpData, dwCount, &dwBytesWritten);
EndPagePrinter (hPrinter);
}
// Inform the spooler that the document is ending.
EndDocPrinter( hPrinter );
}
// Close the printer handle.
ClosePrinter( hPrinter );
}
// Check to see if correct number of bytes were written.
if (!bStatus || (dwBytesWritten != dwCount)) {
bStatus = FALSE;
} else {
bStatus = TRUE;
}
return bStatus;
}
int _tmain(int argc, _TCHAR* argv[])
{
LPTSTR printerName = (LPTSTR)_T("XP-58");
CStringW str = L"unicode";
int bytelen = 2 * str.GetLength();
LPBYTE pByte = new BYTE[bytelen];
memcpy(pByte, str, bytelen);
DWORD count = bytelen;
BOOL result = RawDataToPrinter(printerName, pByte, count);
std::cout << GetLastError() << std::endl;
std::cout << result << std::endl;
system("pause");
return(0);
}
The printer doesn't know that you're finished sending it everything, so it doesn't print.
To finish a line, you need to add the characters "\r\n" to the string.
When you're finished with a page, add "\f" to the string.
Related
I'm using some legacy code to enumerate ports on my machine:
#include <windows.h>
#include <devguid.h>
#include <setupapi.h>
#include <string>
#include <iostream>
#include <assert.h>
bool GetTextProperty( std::string& sProperty,
HDEVINFO dev,
_SP_DEVINFO_DATA* pDeviceInfoData,
DWORD prop )
{
char szBuf[MAX_PATH];
DWORD iPropertySize = 0;
if (SetupDiGetDeviceRegistryProperty(dev, pDeviceInfoData,
prop, 0L, (PBYTE) szBuf, MAX_PATH, &iPropertySize))
{
sProperty = szBuf;
assert( iPropertySize >= sProperty.size() + 1 );
return true;
}
return false;
}
inline bool readRegistryKeyValue( HKEY hKey, const std::string& key, std::string& value )
{
bool res = false;
CHAR szBuffer[512];
DWORD dwBufferSize = sizeof(szBuffer);
ULONG nError = RegQueryValueEx(hKey, key.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
if (ERROR_SUCCESS == nError)
{
value = szBuffer;
res = true;
}
return res;
}
void ListPorts()
{
HDEVINFO hDevInfo;
SP_DEVINFO_DATA DeviceInfoData;
DWORD i;
hDevInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS, 0L, 0L, DIGCF_PRESENT);
if ( hDevInfo == INVALID_HANDLE_VALUE )
{
//Medoc_ReportError(MEDOC_ERROR_HARDWARE_DRIVER_API_FAILED,
// &hDevInfo, sizeof hDevInfo);
assert( false );
}
else
{
// Enumerate through all devices in Set.
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData) != 0; i++)
{
char szBuf[MAX_PATH];
short wImageIdx = 0;
short wItem = 0;
DWORD iPropertySize;
if (SetupDiGetDeviceRegistryProperty(hDevInfo, &DeviceInfoData,
SPDRP_FRIENDLYNAME, 0L, (PBYTE) szBuf, MAX_PATH, &iPropertySize))
{
std::cout << "Smart name: " << szBuf << std::endl;
HKEY hKey = SetupDiOpenDevRegKey(
hDevInfo,
&DeviceInfoData,
DICS_FLAG_GLOBAL,
0,
DIREG_DEV,
KEY_READ );
if ( hKey )
{
std::string portName;
readRegistryKeyValue( hKey, "PortName", portName );
std::cout << "Port name: " << szBuf << std::endl;
for ( DWORD prop = 0; prop != SPDRP_MAXIMUM_PROPERTY; ++prop )
{
std::string temp;
GetTextProperty( temp, hDevInfo, &DeviceInfoData, prop );
std::cout << prop << " : " << temp << std::endl;
}
RegCloseKey(hKey);
}
}
}
}
// Cleanup
SetupDiDestroyDeviceInfoList(hDevInfo);
}
int main( int argc, char* argv[] )
{
ListPorts();
return 0;
}
Among other information, this gives me access to port name (COM*), type (FTDI for instance), VID and PID...
However, when I have many different devices based on a FTDI chip plugged, they all have the same information (SPDRP_HARDWAREID prperty reports FTDIBUS\COMPORT&VID_0403&PID_6015 or FTDIBUS\COMPORT&VID_0403&PID_6010). So I cannot discriminate who is who.
When I use a USB sniffer ("Device Monitoring Studio"), this one is able to report more relevant information withoutestablishing any connection to the ports:
Can this kind of extended information be accessed through Windows API to discriminate by name many devices using the same FTDI chip? Or must I use FTDI driver API to achieve this?
With the help of Ben Voigt and Simon Mourier, I could achieve this, here is the piece of code:
// More includes:
#include <initguid.h>
#include <devpkey.h>
#include <cfgmgr32.h>
// A new dependency:
#pragma comment (lib, "Cfgmgr32.lib")
bool GetDeviceProperty( const std::string& what,
DEVINST dev,
DEVPROPKEY prop )
{
char szDeviceBuf[MAX_PATH];
DEVPROPTYPE type;
ULONG iDevicePropertySize = MAX_PATH;
if ( CM_Get_DevNode_PropertyW(dev,
&prop,
&type,
(PBYTE) szDeviceBuf,
&iDevicePropertySize,
0) == CR_SUCCESS )
{
wchar_t* txt = (wchar_t*) szDeviceBuf;
std::wstring ws(txt);
std::cout << what << " : " << std::string(ws.begin(), ws.end()) << std::endl;
return true;
}
else
{
return false;
}
}
void ListPorts()
{
...
DEVINST devInstParent;
auto status = CM_Get_Parent(&devInstParent, DeviceInfoData.DevInst, 0);
if (status == CR_SUCCESS)
{
ShowDeviceProperty( "Bus reported device description", devInstParent, DEVPKEY_Device_BusReportedDeviceDesc );
ShowDeviceProperty( "Device description", devInstParent, DEVPKEY_Device_DeviceDesc );
}
else
{
continue;
}
...
As you know there is some difference between a process name and it's description, for example the dwm.exe process's description is Desktop Window Manager
I can check the name of the processes with this code:
#include <windows.h>
#include <TlHelp32.h>
#include <Winternl.h>
typedef NTSTATUS (NTAPI *NTQUERYINFORMATIONPROCESS)(
IN HANDLE ProcessHandle,
IN PROCESSINFOCLASS ProcessInformationClass,
OUT PVOID ProcessInformation,
IN ULONG ProcessInformationLength,
OUT PULONG ReturnLength OPTIONAL
);
int main()
{
PEB Peb = {0};
DWORD dwSize = 0;
DWORD dwPID = 0;
HANDLE hProcess = NULL;
HANDLE hProcessSnap = NULL;
WCHAR PsPath[MAX_PATH] = {0};
WCHAR wszProcName[20] = L"dwm.exe"; //Desktop Window Manager
PROCESSENTRY32 PsEntry32 = {0};
PROCESS_BASIC_INFORMATION PsBasicInfo = {0};
RTL_USER_PROCESS_PARAMETERS RtlUserPsParams = {0};
NTQUERYINFORMATIONPROCESS NtFunction = NULL;
if((hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) != INVALID_HANDLE_VALUE)
{
PsEntry32.dwSize = sizeof(PROCESSENTRY32);
if(!Process32First(hProcessSnap, &PsEntry32))
{
CloseHandle(hProcessSnap);
return FALSE;
}
do
{
if(lstrcmpiW(PsEntry32.szExeFile, wszProcName) == 0)
{
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, PsEntry32.th32ProcessID);
if(hProcess != INVALID_HANDLE_VALUE)
{
NtFunction = (NTQUERYINFORMATIONPROCESS)GetProcAddress(LoadLibraryW(L"ntdll.dll"), "NtQueryInformationProcess");
if(NtFunction)
{
if(NtFunction(hProcess, ProcessBasicInformation, &PsBasicInfo, sizeof(PROCESS_BASIC_INFORMATION), &dwSize) == ERROR_SUCCESS)
{
ReadProcessMemory(hProcess, PsBasicInfo.PebBaseAddress, &Peb, sizeof(PEB), (SIZE_T*)&dwSize);
ReadProcessMemory(hProcess, Peb.ProcessParameters, &RtlUserPsParams, sizeof(RTL_USER_PROCESS_PARAMETERS), (SIZE_T*)&dwSize);
ReadProcessMemory(hProcess, RtlUserPsParams.ImagePathName.Buffer, PsPath, RtlUserPsParams.ImagePathName.Length, (SIZE_T*)&dwSize);
dwPID = PsEntry32.th32ProcessID;
}
}
CloseHandle(hProcess);
}
}
}while(Process32Next(hProcessSnap, &PsEntry32));
CloseHandle(hProcessSnap);
}
return 0;
}
now I want to check the processes description
Is it possible to get all processes description one by one and check them?
I use ToolHelp32Snapshot() to get the module path instead of your PEB method, following that I:
GetFileVersionInfoSizeA() to get the size of the version structure
GetFileVersionInfoA() to pull the data from that structure into a local char array.
VerQueryValue() with "\VarFileInfo\Translation" to get the language code pages
Then I loop through the different language code pages to create the subblock string required for the next query.
Then I use VerQueryValue() with the correct language code page inserted inside the sub block and store the result into another char array.
Then we print this string to console.
#include <iostream>
#include <string>
#include <Windows.h>
#include <TlHelp32.h>
#include <strsafe.h>
#pragma comment(lib,"Version.lib")
std::string GetModulePath(std::string moduleName, DWORD procId)
{
std::string path;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, procId);
if (hSnap != INVALID_HANDLE_VALUE)
{
MODULEENTRY32 modEntry{};
modEntry.dwSize = sizeof(modEntry);
if (Module32First(hSnap, &modEntry))
{
do
{
if (!_stricmp(modEntry.szModule, moduleName.c_str()))
{
path = modEntry.szExePath;
break;
}
} while (Module32Next(hSnap, &modEntry));
}
}
CloseHandle(hSnap);
return path;
}
std::string GetFilePath(std::string procName)
{
std::string path;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 procEntry;
procEntry.dwSize = sizeof(procEntry);
if (Process32First(hSnap, &procEntry))
{
do
{
if (!_stricmp(procEntry.szExeFile, procName.c_str()))
{
path = GetModulePath(procName, procEntry.th32ProcessID);
break;
}
} while (Process32Next(hSnap, &procEntry));
}
}
CloseHandle(hSnap);
return path;
}
struct LANGANDCODEPAGE {
WORD wLanguage;
WORD wCodePage;
};
int main()
{
std::string path = GetFilePath("notepad++.exe");
DWORD verSize = GetFileVersionInfoSizeA(path.c_str(), 0);
char* data = new char[verSize]{ 0 };
GetFileVersionInfoA(path.c_str(), 0, verSize, data);
UINT length;
LANGANDCODEPAGE* lpTranslate;
VerQueryValue(data, "\\VarFileInfo\\Translation", (LPVOID*)&lpTranslate, &length);
char SubBlock[50]{ 0 };
for (unsigned int i = 0; i < (length / sizeof(struct LANGANDCODEPAGE)); i++)
{
HRESULT result = StringCchPrintf(SubBlock, 50,
TEXT("\\StringFileInfo\\%04x%04x\\FileDescription"),
lpTranslate[i].wLanguage,
lpTranslate[i].wCodePage);
char* description = new char[0x100]{ 0 };
UINT length2;
VerQueryValue(data, SubBlock, (LPVOID*)&description, &length2);
std::cout << description << "\n";
}
getchar();
return 0;
}
Must run as administrator, and only tested on x86.
Actually I am working with Qt printing and need to send the RAW command (ESCP command) to printer. After did some search and I found that I need to use the Windows API to do it.
Refer to this thread : win32-c-print-string-to-printer
I have created the code like below :
const QString pName = "EPSON LX-300+ /II";
LPBYTE lpData;
BOOL bStatus = FALSE;
HANDLE hPrinter = NULL;
DOC_INFO_1 DocInfo;
DWORD dwPrtJob = 0L;
DWORD dwBytesWritten = 0L;
LPTSTR printerName = new wchar_t[pName.length() + 1];
pName.toWCharArray(printerName);
printerName[pName.length()] = '\0';
QString so = "\x1b#Is it works?";
QByteArray ba = so.toUtf8();
lpData = (unsigned char*)(ba.data());
DWORD dwCount = ba.length();
qDebug() << so;
bStatus = OpenPrinter(printerName, &hPrinter, NULL);
if(bStatus) {
DocInfo.pDocName = (LPTSTR)_T("My Document");
DocInfo.pOutputFile = NULL;
DocInfo.pDatatype = (LPTSTR)_T("RAW");
dwPrtJob = StartDocPrinter (
hPrinter,
1,
(LPBYTE)&DocInfo);
qDebug() << GetLastError();
if (dwPrtJob > 0) {
qDebug() << "COMMAND";
// Send the data to the printer.
bStatus = WritePrinter (
hPrinter,
lpData,
dwCount,
&dwBytesWritten);
}
qDebug() << dwCount;
qDebug() << dwBytesWritten;
EndDocPrinter (hPrinter);
// Close the printer handle.
bStatus = ClosePrinter(hPrinter);
qDebug() << bStatus;
}
if (!bStatus || (dwCount != dwBytesWritten)) {
bStatus = FALSE;
} else {
bStatus = TRUE;
}
delete printerName;
And the code failed on StartDocPrinter, it returning 0 which mean failed. And using the GetLastError(), the function return 1804. And refer to this, the error is ERROR_INVALID_DATATYPE. I am not sure what error is it. And i try to use different DocInfo.pDatatype to "RAW", "TEXT", and "XPS_PASS", the result is the same.
Is there anything I can do how to fix it?
DOC_INFO_1 DocInfo;
DocInfo.pDocName = (LPTSTR)_T("My Document");
DocInfo.pOutputFile = NULL;
DocInfo.pDatatype = (LPTSTR)_T("RAW");
This casting boils down to
DocInfo.pDocName = (wchar_t*)L"My Document";
...
Where pDocName is declared as wchar_t* This is wrong and the cast simply hides the errors and warnings. Try to avoid Microsoft T macro altogether, these macros are outdated and useless. Use C++ char and wchar_t* instead. To declare UTF16 wide char string in Windows, use the L prefix. The correct usage is as follows:
DOC_INFO_1 DocInfo;
wchar_t docName[100], dataType[100];
wcscpy_s(docName, 100, L"Print Job");
wcscpy_s(dataType, 100, L"RAW");
DocInfo.pDocName = docName;
DocInfo.pOutputFile = NULL;
DocInfo.pDatatype = dataType;
Example:
const QString pName = "EPSON LX-300+ /II";
wchar_t printerName[100];
pName.toWCharArray(printerName);
pName[pName.length()] = '\0';
HANDLE hprinter;
if (OpenPrinter(printerName, &hprinter, NULL))
{
DOC_INFO_1 DocInfo;
wchar_t docName[100], dataType[100];
wcscpy_s(docName, 100, L"Print Job");
wcscpy_s(dataType, 100, L"RAW");
DocInfo.pDocName = docName;
DocInfo.pOutputFile = NULL;
DocInfo.pDatatype = dataType;
DWORD printJob = StartDocPrinter(hprinter, 1, (LPBYTE)&DocInfo);
if (printJob && StartPagePrinter(hprinter))
{
MessageBox(0, L"StartPagePrinter OKAY", 0, 0);
DWORD written = 0;
int buflen = 100;
char *buf = new char[buflen];
strcpy_s(buf, buflen, "123");
if (WritePrinter(hprinter, buf, 3, &written))
MessageBox(0, L"OKAY", 0, 0);
delete[]buf;
EndPagePrinter(hprinter);
EndDocPrinter(hprinter);
}
ClosePrinter(hprinter);
}
I'd like to have a function that allows me to read the memory of another process.
I was thinking about something like this (pseudo code):
staticAddress = 0x026E0DC4
processId = GetProcessIdByName(processName)
processHandle = GetProcessHandle(processId)
processBaseAddress = GetBaseAddress(processHandle)
addressToRead = processBaseAddress+staticAddress
readValueAsInt = ReadMemoryInt(processHandle, addressToRead)
readValueAsFloat = ReadMemoryFloat(processHandle, addressToRead)
readValueAsString = ReadMemoryString(processHandle, addressToRead)
Would that even be possible?
Here is what I got so far:
#include <Windows.h>
#include <conio.h>
#include <tlhelp32.h>
#include <string>
#include <psapi.h>
#pragma comment( lib, "psapi" )
int GetProcessId(char* ProcName) {
PROCESSENTRY32 pe32;
HANDLE hSnapshot = NULL;
pe32.dwSize = sizeof( PROCESSENTRY32 );
hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( Process32First( hSnapshot, &pe32 ) ) {
do {
if( strcmp( pe32.szExeFile, ProcName ) == 0 )
break;
} while( Process32Next( hSnapshot, &pe32 ) );
}
if( hSnapshot != INVALID_HANDLE_VALUE )
CloseHandle( hSnapshot );
return pe32.th32ProcessID;
}
int GetModuleBase(HANDLE processHandle, string &sModuleName)
{
HMODULE *hModules;
char szBuf[50];
DWORD cModules;
DWORD dwBase = -1;
//------
EnumProcessModules(processHandle, hModules, 0, &cModules);
hModules = new HMODULE[cModules/sizeof(HMODULE)];
if(EnumProcessModules(processHandle, hModules, cModules/sizeof(HMODULE), &cModules)) {
for(int i = 0; i < cModules/sizeof(HMODULE); i++) {
if(GetModuleBaseName(processHandle, hModules[i], szBuf, sizeof(szBuf))) {
if(sModuleName.compare(szBuf) == 0) {
dwBase = (DWORD)hModules[i];
break;
}
}
}
}
delete[] hModules;
return dwBase;
}
int ReadMemoryInt(HANDLE processHandle, LPCVOID address) {
//LPVOID buffer = ??;
//SIZE_T size = ??;
SIZE_T NumberOfBytesToRead = 4; //??
ReadProcessMemory(processHandle, address, buffer, size, NumberOfBytesToRead)
return buffer; //??
}
int ReadMemoryFloat(HANDLE processHandle, LPCVOID address) {
//LPVOID buffer = ??;
//SIZE_T size = ??;
SIZE_T NumberOfBytesToRead = 8; //??
ReadProcessMemory(processHandle, address, buffer, size, NumberOfBytesToRead)
return buffer; //??
}
int ReadMemoryString(HANDLE processHandle, LPCVOID address) {
//LPVOID buffer = ??;
//SIZE_T size = ??;
SIZE_T NumberOfBytesToRead = 999; //??
ReadProcessMemory(processHandle, address, buffer, size, NumberOfBytesToRead)
return buffer; //??
}
int main()
{
//read an integer from "Program.exe"+0x05D8A3C4
int address = 0x05D8A3C4;
char* processName = "Program.exe";
int processId = GetProcessId(processName);
HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, false, processId);
int processBaseAddress = GetModuleBase(processHandle, (string)"Program.exe";
LPCVOID actualAddress = processBaseAddress+address;
int readValue = ReadMemory(processHandle, actualAddress);
std::cout << readValue << std::endl;
CloseHandle(processHandle);
return 0;
}
As you can see form the question marks in the code I'm really unsure about the "buffer" and "size" parameters of ReadProcessMemory. I'd really appreciate it if someone could help me figuring this out.
https://github.com/T-vK/Memory-Hacking-Class
Is a pretty simple class to do all that and even more.
Here is a list with all the methods it supports:
GetProcessId()
GetModuleBase()
SetPrivilege()
GetDebugPrivileges()
ReadInt()
GetPointerAddress()
ReadPointerInt()
ReadFloat()
ReadPointerFloat()
ReadText()
ReadPointerText()
Example usage:
#include "Memory.hpp"
using std::string;
int main() {
char* TARGET_PROCESS_NAME = "League of Legends.exe";
int GAME_VERSION_MODULE_OFFSET = 0x2A1D738; // [Base address of 'League of Legends.exe']+0x2A1D738 (address of a string containing a version number)
Memory Memory;
Memory.GetDebugPrivileges();
int processId = Memory.GetProcessId(TARGET_PROCESS_NAME);
HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, false, processId);
int baseAddress = Memory.GetModuleBase(processHandle, (string)TARGET_PROCESS_NAME);
int gameVersionAddress = baseAddress + GAME_VERSION_MODULE_OFFSET;
string gameVersion = Memory.ReadText(processHandle, gameVersionAddress);
std::cout << "Game version: " << gameVersionAddress << std::endl;
cin.get();
return 0;
}
In case you were wondering, yes, I'm the author.
Here is an example for your ReadMemoryInt() function:
int ReadMemoryInt(HANDLE processHandle, LPCVOID address) {
int buffer = 0;
SIZE_T NumberOfBytesToRead = sizeof(buffer); //this is equal to 4
SIZE_T NumberOfBytesActuallyRead;
BOOL err = ReadProcessMemory(processHandle, address, &buffer, NumberOfBytesToRead, &NumberOfBytesActuallyRead);
if (err || NumberOfBytesActuallyRead != NumberOfBytesToRead)
/*an error occured*/ ;
return buffer;
}
The & mean that the address of the variable is passed instead its value.
And in ReadMemoryString() you cannot know the actual size you need to read, you could either read a big block (size 999) or read many little blocks till you get one containing \0.
And if you want to know if it works, you can start it in a debugger and look if the values you expect are returned.
I have asked a similar question previously, but 1. no one answered and 2. it is a bit different. I have managed to get the correct file Path and created a handler by using CreateFile. I have then tried to use the HidD_GetFeature() function, but when I print out the report, it is all in symbols - not letters, numbers or readable sign. Does anyone know why it is doing that?? Here's my code:
/*****************************Mainframe.cpp**************************************/
#include"DeviceManager.h"
int main()
{
int iQuit;
DeviceManager deviceManager;
//deviceManager.ListAllDevices();
deviceManager.GetDevice("8888", "0308");
std::cin >> iQuit;
return 0;
}
/***********************************DeviceManager.h***************************/
#include <windows.h>
//#include <hidsdi.h>
#include <setupapi.h>
#include <iostream>
#include <cfgmgr32.h>
#include <tchar.h>
#include <devpkey.h>
extern "C"{
#include <hidsdi.h>
}
//#pragma comment (lib, "setupapi.lib")
class DeviceManager
{
public:
DeviceManager();
~DeviceManager();
void ListAllDevices();
void GetDevice(std::string vid, std::string pid);
HANDLE PSMove;
byte reportBuffer[57];
GUID guid;
private:
HDEVINFO deviceInfoSet; //A list of all the devices
SP_DEVINFO_DATA deviceInfoData; //A device from deviceInfoSet
SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailedData;
};
/********************************DeviceManager.cpp*********************************/
#include"DeviceManager.h"
DeviceManager::DeviceManager()
{
HidD_GetHidGuid(&guid);
deviceInfoSet = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE); //Gets all Devices
}
DeviceManager::~DeviceManager()
{
}
void DeviceManager::ListAllDevices()
{
DWORD deviceIndex = 0;
deviceInfoData.cbSize = sizeof(deviceInfoData);
while(SetupDiEnumDeviceInfo(deviceInfoSet, deviceIndex, &deviceInfoData))
{
deviceInfoData.cbSize = sizeof(deviceInfoData);
ULONG tcharSize;
CM_Get_Device_ID_Size(&tcharSize, deviceInfoData.DevInst, 0);
TCHAR* deviceIDBuffer = new TCHAR[tcharSize]; //the device ID will be stored in this array, so the tcharSize needs to be big enough to hold all the info.
//Or we can use MAX_DEVICE_ID_LEN, which is 200
CM_Get_Device_ID(deviceInfoData.DevInst, deviceIDBuffer, MAX_PATH, 0); //gets the devices ID - a long string that looks like a file path.
/*
//SetupDiGetDevicePropertyKeys(deviceInfoSet, &deviceInfoData, &devicePropertyKey, NULL, 0, 0);
if( deviceIDBuffer[8]=='8' && deviceIDBuffer[9]=='8' && deviceIDBuffer[10]=='8' && deviceIDBuffer[11]=='8' && //VID
deviceIDBuffer[17]=='0' && deviceIDBuffer[18]=='3' && deviceIDBuffer[19]=='0' && deviceIDBuffer[20]=='8') //PID
{
std::cout << deviceIDBuffer << "\t<-- Playstation Move" << std::endl;
}
else
{
std::cout << deviceIDBuffer << std::endl;
}*/
std::cout << deviceIDBuffer << std::endl;
deviceIndex++;
}
}
void DeviceManager::GetDevice(std::string vid, std::string pid)
{
DWORD deviceIndex = 0;
deviceInfoData.cbSize = sizeof(deviceInfoData);
while(SetupDiEnumDeviceInfo(deviceInfoSet, deviceIndex, &deviceInfoData))
{
deviceInfoData.cbSize = sizeof(deviceInfoData);
ULONG IDSize;
CM_Get_Device_ID_Size(&IDSize, deviceInfoData.DevInst, 0);
TCHAR* deviceID = new TCHAR[IDSize];
CM_Get_Device_ID(deviceInfoData.DevInst, deviceID, MAX_PATH, 0);
if( deviceID[8]==vid.at(0) && deviceID[9]==vid.at(1) && deviceID[10]==vid.at(2) && deviceID[11]==vid.at(3) && //VID
deviceID[17]==pid.at(0) && deviceID[18]==pid.at(1) && deviceID[19]==pid.at(2) && deviceID[20]==pid.at(3)) //PID
{
DWORD deviceInterfaceIndex = 0;
deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
//HDEVINFO deviceInterfaceSet = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_DEVICEINTERFACE);
if(SetupDiEnumDeviceInterfaces(deviceInfoSet, &deviceInfoData, &guid, deviceInterfaceIndex, &deviceInterfaceData))
{
deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
deviceInterfaceDetailedData.cbSize = sizeof(deviceInterfaceDetailedData);
DWORD requiredSize;
SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, NULL, 0, &requiredSize, &deviceInfoData); //Gets the size
SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, &deviceInterfaceDetailedData, requiredSize, NULL, NULL); //Sets the deviceInterfaceDetailedData
//std::cout << deviceInterfaceDetailedData.DevicePath << std::endl;
PSMove = CreateFile(deviceInterfaceDetailedData.DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
reportBuffer[0] = 0;
ULONG reportBufferLength = sizeof(reportBuffer);
HidD_GetFeature(PSMove, &reportBuffer, reportBufferLength);
std::cout << reportBuffer << std::endl;
//deviceInterfaceIndex++;
}
break;
}
deviceIndex++;
}
}
the HidD_GetFeature() function is at the bottom of this huge block of code.
UPDATE: I've managed to print the report now, but it is just a random 8 bit hex. Everytime I close the program down and run it again, it prints out different results. Why's that?
The ListAllDevices() function isn't displaying the info correctly because you're outputting a wchar_t* to std::cout. You need to use std::wcout for wide chars.