Last Modification: December 11, 1999

How do I change the default printer?

The following code illustrates the technique to do it:


int CALLBACK WinMain( HINSTANCE hInst, HINSTANCE hPrevInst,
		LPSTR lpCmdLine, int nShowCmd )
{
	/* Get the port & device settings for the specified printer */
	char szDeviceString[260];

	/* First (and only) parameter is the printer name */
	lstrcpy( szDeviceString, __argv[1] );
	const int Pos = lstrlen( szDeviceString );

	/* Append a ',' */
	szDeviceString[ Pos ] = ',';

	GetProfileString( "Devices", __argv[1], "",
			&szDeviceString[Pos+1],
			sizeof( szDeviceString ) - (Pos+1) );

	/* Have we got the printer? */
	if ( szDeviceString[Pos+1] != '\0' )
	{
		/* Set the default printer */
		WriteProfileString( "windows", "device", szDeviceString );

		SendMessageTimeout( HWND_BROADCAST, WM_SETTINGCHANGE, 0L,
			(LPARAM)(LPCTSTR)"windows", SMTO_NORMAL,
			1000, NULL );
	}
	else
	{
		MessageBox( NULL, "Printer not found",
			"Set Default Printer Utility",
			MB_OK | MB_ICONERROR );
	}

	return 0;
}

References and samples: