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 = Lusergedik;
// Local account database
LPTSTR lpszDomain = L.;
LPTSTR lpszPassword = L123;
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(LWell, \%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(LThe handle that received the token has been closed.\n);
wprintf(LSomething wrong, the handle cannot be closed! error: %u\n, GetLastError());
Build and run the project. The following screenshot is a sample output.