BOOL ExecuteAsUser(LPCWSTR lpszUserName, LPCWSTR lpszPassword, LPCWSTR lpszApplication, LPCWSTR lpszCmdLine)
{
if(NULL == lpszUserName)
{
return FALSE;
}
if(NULL == lpszApplication)
{
return FALSE;
} BOOL bRet = FALSE;
WCHAR* pUserName = NULL;
WCHAR* pPassword = NULL;
STARTUPINFO si = {sizeof(si)};
PROCESS_INFORMATION pi = {};
WCHAR szApp[MAX_PATH * ] = {}; // Check User Name
size_t nLen = wcslen(lpszUserName) + ;
pUserName = new WCHAR[nLen];
StringCchPrintfW(pUserName, nLen, L"%s", lpszUserName); // Check Password
nLen = (NULL != lpszPassword) ? (wcslen(lpszPassword) + ) : ;
pPassword = new WCHAR[nLen];
StringCchPrintfW(pPassword, nLen, L"%s", (NULL != lpszPassword) ? lpszPassword : L""); USER_INFO_1 ui;
DWORD dwError = ;
DWORD dwLevel = ;
ui.usri1_name = pUserName;
ui.usri1_password = pPassword;
ui.usri1_priv = USER_PRIV_USER;
ui.usri1_home_dir = NULL;
ui.usri1_comment = NULL;
ui.usri1_flags = UF_SCRIPT;
ui.usri1_script_path = NULL;
// Add User
if(NERR_Success != NetUserAdd(NULL, dwLevel, (LPBYTE)&ui, &dwError))
{
goto _END_;
} if((NULL != lpszCmdLine) && wcslen(lpszCmdLine))
StringCchPrintfW(szApp, _countof(szApp), L"%s %s", lpszApplication, lpszCmdLine);
else
StringCchPrintfW(szApp, _countof(szApp), L"%s", lpszApplication); if(CreateProcessWithLogonW(lpszUserName, NULL, lpszPassword, LOGON_WITH_PROFILE, NULL, szApp, , NULL, NULL, &si, &pi))
{
bRet = TRUE;
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
else
{
dwError = GetLastError();
goto _CLEANUP_;
}
bRet = TRUE; _CLEANUP_:
// Delete User
NetUserDel(NULL, lpszUserName);
_END_:
if(NULL != pPassword)
{
delete[] pPassword;
pPassword = NULL;
}
if(NULL != pUserName)
{
delete[] pUserName;
pUserName = NULL;
}
return bRet;
} // 测试代码
#include "stdafx.h" #include <Windows.h>
#include <lm.h>
#include <strsafe.h>
#pragma comment(lib, "Netapi32.lib") int _tmain(int argc, _TCHAR* argv[])
{
ExecuteAsUser(L"ABC", L"Hello", L"F:\\11.exe", NULL);
return ;
}
参考:http://blog.csdn.net/visualeleven/article/details/7640475