Log on a user to a machine Program Example
The following program example demonstrates how to log on a user to a machine programmatically. It uses the LogonUser() function.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
// Log a user on to the local computer. This computer is logged on as Mike spoon,
// a user with Administrators group, then this program try to log
// on a restricted user named "usergedik" another valid user account
// created in the same machine
int main(int argc, WCHAR **argv)
// "usergedik" is just a restrictive user created
// in the XP machine that runs this program
LPTSTR lpszUsername = L"usergedik";
// Local account database
LPTSTR lpszDomain = L".";
LPTSTR lpszPassword = L"123";
DWORD dwLogonType = LOGON32_LOGON_INTERACTIVE;
DWORD dwLogonProvider = LOGON32_PROVIDER_DEFAULT;
lpszUsername, // Username
lpszDomain, // Domain or server where the Username is reside
lpszPassword, // Plaintext password
dwLogonType, // Type of logon
dwLogonProvider, // The logon provider
&hToken // Pointer to handle that received the token
wprintf(L"Well, \"%s\" user logged on to this machine successfully!\n", lpszUsername);
wprintf(L"%s failed to log on to this machine! error %u\n", lpszUsername, GetLastError());
// TODO: Use the logon token for the desired tasks
if(CloseHandle(hToken) != 0)
wprintf(L"The handle that received the token has been closed.\n");
wprintf(L"Something wrong, the handle cannot be closed! error: %u\n", GetLastError());
Build and run the project. The following screenshot is a sample output.