How to convert LPWSTR to LPBYTE - winapi

I found many informations how to convert LPBYTE to LPWSTR, but no info about reverse process. I have tried do it on my own and tested such methods:
// my_documents declaration:
WCHAR my_documents[MAX_PATH];
//1st
const int size = WideCharToMultiByte(CP_UTF8, 0, my_documents, -1, NULL, 0, 0, NULL);
char *path = (char *)malloc( size );
WideCharToMultiByte(CP_UTF8, 0, my_documents, -1, path, size, 0, NULL);
//2nd
size_t i;
char *pMBBuffer = (char *)malloc( MAX_PATH );
cstombs_s(&i, pMBBuffer, MAX_PATH, my_documents, MAX_PATH-1 );
But when I write them to registry they are unreadable. And this is how I write them to registry:
BOOL SetKeyData(HKEY hRootKey, WCHAR *subKey, DWORD dwType, WCHAR *value, LPBYTE data, DWORD cbData)
{
HKEY hKey;
if(RegCreateKeyW(hRootKey, subKey, &hKey) != ERROR_SUCCESS)
return FALSE;
LSTATUS status = RegSetValueExW(hKey, value, 0, dwType, data, cbData);
if(status != ERROR_SUCCESS)
{
RegCloseKey(hKey);
return FALSE;
}
RegCloseKey(hKey);
return TRUE;
}
SetKeyData(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", REG_SZ, L"My program", (LPBYTE)path, size)
There is no problem with conversion, but when I try to write this to registry I get some strange chars

When you are writing a string to the wide registry functions you should not convert but pass a normal WCHAR*, just cast to LPBYTE. Just remember to get the size correct. LPBYTE is really for when you write a binary blob, every other type has to be casted...

Related

Why timeout param doesn't work in GetAddrInfoExW()?

When I try to call:
timeval timeout{ 0, 999 };
::GetAddrInfoExW(L"my_name", L"", NS_DNS, nullptr, nullptr, &pResult, &timeout, nullptr, nullptr, nullptr);
I got 10022 "Invalid params".
However, if I replace "&timeout" with "nullptr", I got 0 (OK).
Why the timeout causes EINVAL error?
UNICODE macro is defined, my system is Windows 10.
if timeout not 0, the lpOverlapped must be also not 0. the code can be next
#include <ws2tcpip.h>
struct QUERY_CONTEXT : OVERLAPPED
{
PADDRINFOEX _pResult;
ULONG _dwThreadId = GetCurrentThreadId();
~QUERY_CONTEXT()
{
if (PADDRINFOEX pResult = _pResult)
{
FreeAddrInfoEx(_pResult);
}
}
static void CALLBACK QueryCompleteCallback(
_In_ ULONG dwError,
_In_ ULONG /*dwBytes*/,
_In_ OVERLAPPED* lpOverlapped
)
{
static_cast<QUERY_CONTEXT*>(lpOverlapped)->OnComplete(dwError);
}
void OnComplete(_In_ ULONG dwError)
{
DbgPrint("OnComplete(%u)\n");
if (PADDRINFOEX pResult = _pResult)
{
do
{
WCHAR buf[64];
ULONG len = _countof(buf);
if (!WSAAddressToStringW(pResult->ai_addr, (ULONG)pResult->ai_addrlen, 0, buf, &len))
{
DbgPrint("%S\n", buf);
}
} while (pResult = pResult->ai_next);
}
PostThreadMessageW(_dwThreadId, WM_QUIT, dwError, 0);
delete this;
}
ULONG Query(_In_ PCWSTR pName, _In_opt_ timeval *timeout)
{
ULONG dwError = GetAddrInfoExW(pName, 0, NS_DNS, 0, 0,
&_pResult, timeout, this, QueryCompleteCallback, 0);
//
// If GetAddrInfoExW() returns WSA_IO_PENDING, GetAddrInfoExW will invoke
// the completion routine. If GetAddrInfoExW returned anything else we must
// invoke the completion directly.
//
if (dwError != WSA_IO_PENDING)
{
QueryCompleteCallback(dwError, 0, this);
}
return dwError;
}
};
///////////////////////////////////////
WSADATA wd;
if (NOERROR == WSAStartup(WINSOCK_VERSION, &wd))
{
if (QUERY_CONTEXT* pqc = new QUERY_CONTEXT {})
{
timeval timeout{ 1 };
pqc->Query(L"stackoverflow.com", &timeout);
}
MessageBoxW(0, 0, 0, 0);
WSACleanup();
}
also for dns query more efficient direct use DnsQueryEx function (GetAddrInfoExW internally call DnsQueryEx, but before this - alot of another code executed)

Identifying USB COM device using Windows APIs

I connect to Arduino Uno R3 via a WinAPI handle.
std::string name = "COM5";
this->handle = CreateFile(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
How can I safely distinguish Arduino so I am not communicating with something different or at least get its name, preferably without third party libraries? After a research I found several APIs (QueryDosDevice and NtQueryObject), however I don't know how can I implement those in my code.
EDIT: I am now able to enumerate USB devices, however I have the exact opposite problem. I do not know how to CreateFile from these:
EXTERN_C const DEVPROPKEY DECLSPEC_SELECTANY DEVPKEY_Device_BusReportedDeviceDesc = { { 0x540b947e, 0x8b40, 0x45bc, { 0xa8, 0xa2, 0x6a, 0x0b, 0x89, 0x4c, 0xbd, 0xa2 } }, 4 };
typedef BOOL(WINAPI *FN_SetupDiGetDeviceProperty)(
__in HDEVINFO DeviceInfoSet,
__in PSP_DEVINFO_DATA DeviceInfoData,
__in const DEVPROPKEY *PropertyKey,
__out DEVPROPTYPE *PropertyType,
__out_opt PBYTE PropertyBuffer,
__in DWORD PropertyBufferSize,
__out_opt PDWORD RequiredSize,
__in DWORD Flags
);
std::vector<device> usbenumerator::ListDevices()
{
DWORD dwSize;
DEVPROPTYPE ulPropertyType;
CONFIGRET status;
HDEVINFO hDevInfo;
SP_DEVINFO_DATA DeviceInfoData;
char szDeviceInstanceID[MAX_DEVICE_ID_LEN];
WCHAR szBuffer[4096];
FN_SetupDiGetDeviceProperty GetDeviceProperty = (FN_SetupDiGetDeviceProperty)(GetProcAddress(GetModuleHandle("setupapi.dll"), "SetupDiGetDevicePropertyW"));
hDevInfo = SetupDiGetClassDevs(NULL, "USB", NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT);
std::vector<device> output;
if (hDevInfo == INVALID_HANDLE_VALUE)
{
return output;
}
for (int i = 0; ; i++)
{
device dev;
DeviceInfoData.cbSize = sizeof(DeviceInfoData);
if (!SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData))
{
break;
}
status = CM_Get_Device_ID(DeviceInfoData.DevInst, szDeviceInstanceID, MAX_PATH, 0);
if (status != CR_SUCCESS)
{
continue;
}
std::string deviceID = szDeviceInstanceID;
dev.id = deviceID;
if (GetDeviceProperty && GetDeviceProperty(hDevInfo, &DeviceInfoData, &DEVPKEY_Device_BusReportedDeviceDesc, &ulPropertyType, (BYTE*) szBuffer, sizeof(szBuffer), &dwSize, 0))
{
if (GetDeviceProperty(hDevInfo, &DeviceInfoData, &DEVPKEY_Device_BusReportedDeviceDesc, &ulPropertyType, (BYTE*)szBuffer, sizeof(szBuffer), &dwSize, 0))
{
_bstr_t b(szBuffer);
const char* cBusReportedDesc = b;
std::string busReportedDesc = cBusReportedDesc;
dev.busReportedDesc = busReportedDesc;
}
}
output.push_back(dev);
}
return output;
}
I think I got it: I am basically making my own copy of the SymbolicName key in the Windows registry (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\**YOUR_DEVICE_ID**\Device Parameters, for example HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_2341&PID_0001\75633313233351E0A1E1\Device Parameters)
// Error checking omitted
CM_Get_Device_ID(DeviceInfoData.DevInst, szDeviceInstanceID, MAX_PATH, 0);
std::string deviceID = szDeviceInstanceID;
std::string did = deviceID;
// Convert all backslashes to hash signs
std::replace(did.begin(), did.end(), '\\', '#');
// The GUID seems to stay the same: https://learn.microsoft.com/en-us/windows-hardware/drivers/install/guid-devinterface-usb-device
std::string rid = "\\??\\" + did + "#{a5dcbf10-6530-11d2-901f-00c04fb951ed}";
handle = CreateFile(rid, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

Creating new registry entries in vc++

I am trying to create new registry entries which copies the certain registry values from HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings. I am successfully able to create the new registry entries but the values and sub key are not copied.I am not able to figure out where I have done the mistake. Please help me out.below is my code:
#include<tchar.h>
#include<conio.h>
#include<Windows.h>
#include<Winreg.h>
#include<WinBase.h >
#include<TlHelp32.h>
#define MAX_PATH 1024
DWORD MigrateProxy;
DWORD ProxyEnable;
DWORD ProxyHTTP11;
LPWSTR AutoConfigURL=0;
LPWSTR ProxyServer=0;
LPWSTR ProxyOverride=0;
void CopyRegistryProxySettings(HKEY hKeyRoot, LPCWSTR Subkey, LPCWSTR ValueKey);
bool CreateNewRegistry(HKEY hKeyRoot);
void main()
{
bool bStatusFlag = false,bReadFlag=false,bWriteFlag=false;
LPCWSTR lpSubKey = L"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
LPCWSTR lpValueName = L"AutoConfigURL";
CopyRegistryProxySettings(HKEY_CURRENT_USER, lpSubKey,lpValueName);
bStatusFlag = CreateNewRegistry(HKEY_CURRENT_USER);
//bWriteFlag = RestoreOlderRegistry()
getch();
}
void CopyRegistryProxySettings(HKEY hKeyRoot, LPCWSTR Subkey, LPCWSTR ValueKey)
{
HKEY hKey = NULL;
wchar_t buffer[MAX_PATH];
DWORD dwBufLen;
DWORD dwValue = 0;
DWORD dwDataSize = sizeof(DWORD);
memset(buffer, 0, sizeof buffer);
dwBufLen = MAX_PATH;
if ( ERROR_SUCCESS == RegOpenKeyEx(hKeyRoot, Subkey, 0, KEY_ALL_ACCESS , &hKey))
{
if(ERROR_SUCCESS == RegQueryValueEx(hKey,L"AutoConfigURL",NULL,NULL,(BYTE*)buffer,&dwBufLen))
{
AutoConfigURL = buffer;
memset(buffer, 0, sizeof buffer);
}
if(ERROR_SUCCESS == RegQueryValueEx(hKey,L"ProxyServer",NULL,NULL,(BYTE*)buffer,&dwBufLen))
{
ProxyServer = buffer;
memset(buffer, 0, sizeof buffer);
}
if(ERROR_SUCCESS == RegQueryValueEx(hKey,L"ProxyOverride",NULL,NULL,(BYTE*)buffer,&dwBufLen))
{
ProxyOverride = buffer;
memset(buffer, 0, sizeof buffer);
}
if(ERROR_SUCCESS == RegQueryValueEx(hKey,L"MigrateProxy",NULL,NULL,(LPBYTE)&dwValue,&dwDataSize))
{
MigrateProxy = dwValue;
}
if(ERROR_SUCCESS == RegQueryValueEx(hKey,L"ProxyEnable",NULL,NULL,(LPBYTE)&dwValue,&dwDataSize))
{
ProxyEnable = dwValue;
}
if(ERROR_SUCCESS == RegQueryValueEx(hKey,L"ProxyHttp1.1",NULL,NULL,(LPBYTE)&dwValue,&dwDataSize))
{
ProxyHTTP11 = dwValue;
}
}
}
bool CreateNewRegistry(HKEY hKeyRoot)
{
HKEY hKey;
if (RegCreateKeyEx(HKEY_CURRENT_USER, L"Software\\NewSettings\\Internet Settings", NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL) == ERROR_SUCCESS)
{
RegSetValueEx(hKey, L"AutoConfigURL", NULL,REG_SZ,(BYTE*)AutoConfigURL, (DWORD)((lstrlen(AutoConfigURL)+1)*sizeof(TCHAR)));
RegSetValueEx(hKey, L"ProxyServer", NULL,REG_SZ,(BYTE*)ProxyServer, (DWORD)((lstrlen(ProxyServer)+1)*sizeof(TCHAR)));
RegSetValueEx(hKey, L"ProxyOverride", NULL,REG_SZ,(BYTE*)ProxyOverride, (DWORD)((lstrlen(ProxyOverride)+1)*sizeof(TCHAR)));
RegSetValueEx(hKey, L"MigrateProxy", NULL,REG_DWORD,(BYTE*)MigrateProxy, (DWORD)sizeof(MigrateProxy));
RegSetValueEx(hKey, L"ProxyEnable", NULL,REG_DWORD,(BYTE*)ProxyEnable, (DWORD)sizeof(ProxyEnable));
RegSetValueEx(hKey, L"ProxyHTTP1.1", NULL, REG_DWORD,(BYTE*)ProxyHTTP11, (DWORD)sizeof(ProxyHTTP11));
}
return 1;
}

BHO object won't load, probable registration trouble?

I can't get Internet Explorer or Windows Explorer to load this BHO. Sure there's no COM objects that can be created, but Explorer can't know that until it loads the DLL and checks, but LoadLibrary isn't getting called.
The message box shows when I run regsvr32.
Windows Version = 8.1
Internet Epxlorer Version = 11
Enhance Protected Mode on or off doesn't seem to make a difference.
#include <windows.h>
#include <olectl.h>
#include <stddef.h>
#include <string.h>
#define wstrlen wcslen
HINSTANCE me;
DWORD WINAPI M4(void *junk)
{
MessageBox(NULL, "Loaded", "bho", 0);
}
BOOL WINAPI DllMain(HINSTANCE hInstDll, DWORD fdwReason, LPVOID lpReserved)
{
wchar_t mainexe[1024];
if (fdwReason == DLL_PROCESS_ATTACH) {
me = hInstDll;
DisableThreadLibraryCalls(me);
/* GetModuleFileNameW(NULL, mainexe, 1024); */
/* len = wstrlen(mainexe); */
HANDLE th = CreateThread(NULL, 32768, M4, NULL, 0, NULL);
}
return TRUE;
}
STDAPI DllGetClassObject(REFIID rclsid,REFIID riid,LPVOID *ppv)
{
return CLASS_E_CLASSNOTAVAILABLE;
}
STDAPI DllCanUnloadNow()
{
return FALSE;
}
const char *CLSID_NAME = "CLSID\\{2D3E480A-0000-0000-0000-64756D796C6472}";
const char *CLSID_IPS32 = "CLSID\\{2D3E480A-0000-0000-0000-64756D796C6472}\\InProcServer32";
const char *BHO = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects\\{2D3E480A-0000-0000-0000-64756D796C6472}";
const wchar_t *name = L"Redacted BHO";
const char *apt = "Apartment";
STDAPI DllRegisterServer()
{
HKEY hk;
wchar_t dllpath[1024];
GetModuleFileNameW(me,dllpath,1024);
if (RegCreateKeyEx(HKEY_CLASSES_ROOT, CLSID_NAME, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hk, NULL) != ERROR_SUCCESS)
return SELFREG_E_CLASS;
RegSetValueExW(hk, NULL, 0, REG_SZ, (const BYTE *)(name), (wstrlen(name) + 1) << 1);
RegCloseKey(hk);
if (RegCreateKeyEx(HKEY_CLASSES_ROOT, CLSID_IPS32, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hk, NULL) != ERROR_SUCCESS)
return SELFREG_E_CLASS;
RegSetValueExW(hk, NULL, 0, REG_SZ, (const BYTE *)(dllpath), (wstrlen(dllpath) + 1) << 1);
RegSetValueEx(hk, "ThreadingModel", 0, REG_SZ, (const BYTE *)(apt), 10);
RegCloseKey(hk);
if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, BHO, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hk, NULL) != ERROR_SUCCESS)
return SELFREG_E_CLASS;
RegCloseKey(hk);
return S_OK;
}
STDAPI DllUnregisterServer()
{
RegDeleteKey(HKEY_LOCAL_MACHINE, BHO);
RegDeleteKey(HKEY_CLASSES_ROOT, CLSID_IPS32);
RegDeleteKey(HKEY_CLASSES_ROOT, CLSID_NAME);
}
For IE11 in enhanced protected mode (EPM), the registry must be updated with:
HKEY_CLASSES_ROOT\CLSID\{your BHO CLSID}\Implemented
Categories\{59FB2056-D625-48D0-A944-1A85B5AB2640}

I need getRTF() example for win32 api richedit control [duplicate]

(Sorry for my crazy English)
I want to get all the text in Rich Edit with RTF format, not plain text to a variable. I tried SendMessage() with EM_STREAMOUT to write directly Rich Edit to file, but I can't save the content to specific variables, for example LPWSTR. Please remember, only Win API, not MFC. Thanks for you help!
You can pass your variable to the EM_STREAMOUT callback so it can be updated as needed, eg:
DWORD CALLBACK EditStreamOutCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
std::stringstream *rtf = (std::stringstream*) dwCookie;
rtf->write((char*)pbBuff, cb);
*pcb = cb;
return 0;
}
.
std::stringstream rtf;
EDITSTREAM es = {0};
es.dwCookie = (DWORD_PTR) &rtf;
es.pfnCallback = &EditStreamOutCallback;
SendMessage(hRichEditWnd, EM_STREAMOUT, SF_RTF, (LPARAM)&es);
// use rtf.str() as needed...
Update: to load RTF data into the RichEdit control, use EM_STREAMIN, eg:
DWORD CALLBACK EditStreamInCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
std::stringstream *rtf = (std::stringstream*) dwCookie;
*pcb = rtf->readsome((char*)pbBuff, cb);
return 0;
}
.
std::stringstream rtf("...");
EDITSTREAM es = {0};
es.dwCookie = (DWORD_PTR) &rtf;
es.pfnCallback = &EditStreamInCallback;
SendMessage(hRichEditWnd, EM_STREAMIN, SF_RTF, (LPARAM)&es);
Using the EM_STREAMOUT message is the answer.
Here is the simplest example that I can construct to demonstrate. This will save the contents of a rich edit control to a file.
DWORD CALLBACK EditStreamOutCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
HANDLE hFile = (HANDLE)dwCookie;
DWORD NumberOfBytesWritten;
if (!WriteFile(hFile, pbBuff, cb, &NumberOfBytesWritten, NULL))
{
//handle errors
return 1;
// or perhaps return GetLastError();
}
*pcb = NumberOfBytesWritten;
return 0;
}
void SaveRichTextToFile(HWND hWnd, LPCWSTR filename)
{
HANDLE hFile = CreateFile(filename, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
//handle errors
}
EDITSTREAM es = { 0 };
es.dwCookie = (DWORD_PTR) hFile;
es.pfnCallback = EditStreamOutCallback;
SendMessage(hWnd, EM_STREAMOUT, SF_RTF, (LPARAM)&es);
CloseHandle(hFile);
if (es.dwError != 0)
{
//handle errors
}
}

Resources