I have this test code:
int main(int argc, char *argv[])
{
setlocale(LC_ALL, "");
std::string user;
std::string pass;
std::cout << "user: ";
getline(std::cin, user);
std::cout << "\npass: ";
getline(std::cin, pass);
std::cout << std::endl;
std::wstring suser = std::wstring(user.begin(), user.end());
LPCWSTR su = suser.c_str();
std::wstring spass = std::wstring(pass.begin(), pass.end());
LPCWSTR sp = spass.c_str();
DWORD dwSize = 0;
HANDLE hToken ;
LPVOID lpvEnv = 0;
PROCESS_INFORMATION pi = {0};
STARTUPINFO si = {0};
WCHAR szUserProfile[256] = L"";
si.cb = sizeof(STARTUPINFO);
if (!LogonUser(su, L".", sp, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, &hToken))
qDebug() << "LogonUser";
if (!CreateEnvironmentBlock(&lpvEnv, hToken, TRUE))
qDebug() << "CreateEnvironmentBlock";
dwSize = sizeof(szUserProfile)/sizeof(WCHAR);
if (!GetUserProfileDirectory(hToken, szUserProfile, &dwSize))
qDebug() << "GetUserProfileDirectory";
WCHAR app[] = L"\"C:\\Program Files (x86)\\Adobe\\Reader 11.0\\Reader\\AcroRd32.exe\" \"C:\\Users\\UD\\Desktop\\insect immunity.pdf\"";
if (!CreateProcessWithLogonW(su, L".", sp,
LOGON_WITH_PROFILE, NULL, app,
CREATE_UNICODE_ENVIRONMENT, lpvEnv, szUserProfile,
&si, &pi)) {
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("failed with error %d: %s"), dw, lpMsgBuf);
qDebug() << QString::fromWCharArray((LPTSTR)lpDisplayBuf);
}
if (!DestroyEnvironmentBlock(lpvEnv))
qDebug() << "DestroyEnvironmentBlock";
CloseHandle(hToken);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
system("pause");
return 0;
}
On PC of my friend it works always fine. On my PC it works sometimes! Only sometimes, most of times it produces 1783 error. I tried to remove some services on my PC, but that didn't helps. I need that code works on many other PCs, so I need to understand why this error appears and how to fix it.
Helps to set enviroment to NULL in CreateProcessWithLogonW/