Code:
// Adds program to startup folder
#include <windows.h>
#include <objbase.h>
#include <shlobj.h>
#include <objidl.h>
#include <shlwapi.h>
#include <stdio.h>
#pragma comment(lib,"uuid.lib")
#pragma comment(lib,"ole32.lib")
#pragma comment(lib,"shell32.lib")
#pragma comment(lib,"user32.lib")
HRESULT CreateMyStartupShortcut (
LPCTSTR lpCommandLine,
LPCTSTR lpArguments,
WORD wHotKey,
LPCTSTR lpIconLocation,
int iIconIndex,
int iShow,
LPCTSTR lpWorkingDirectory,
LPCTSTR lpDescription,
LPCTSTR lpLinkName )
{
HRESULT hres;
IShellLink *psl;
BOOL bUninitializeCom = FALSE;
if( (lpCommandLine == NULL) || (lpLinkName == NULL))
return E_INVALIDARG;
if ( SUCCEEDED(CoInitialize(NULL)))
bUninitializeCom = TRUE;
hres = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLink, (void **) &psl);
if( SUCCEEDED(hres) )
{
IPersistFile *ppf;
psl->lpVtbl->SetPath( psl, lpCommandLine );
if( lpDescription != NULL )
psl->lpVtbl->SetDescription( psl, lpDescription );
if( lpArguments != NULL )
psl->lpVtbl->SetArguments( psl, lpArguments );
if( wHotKey != 0 )
psl->lpVtbl->SetHotkey( psl, wHotKey );
if( lpIconLocation != NULL )
psl->lpVtbl->SetIconLocation( psl, lpIconLocation, iIconIndex);
if( iShow != -1 )
psl->lpVtbl->SetShowCmd( psl, iShow );
if( lpWorkingDirectory != NULL )
psl->lpVtbl->SetWorkingDirectory( psl, lpWorkingDirectory );
hres = psl->lpVtbl->QueryInterface( psl, &IID_IPersistFile, (void **) &ppf );
if( SUCCEEDED(hres))
{
#ifndef UNICODE
WCHAR wsz[MAX_PATH];
MultiByteToWideChar( CP_ACP, 0, lpLinkName, -1, wsz, MAX_PATH);
#else
LPCWSTR wsz = lpLinkName;
#endif
hres = ppf->lpVtbl->Save( ppf, wsz, TRUE );
ppf->lpVtbl->Release(ppf);
}
psl->lpVtbl->Release(psl);
}
if (bUninitializeCom)
CoUninitialize();
return hres;
}
BOOL GetFolderPath(LPTSTR szFolder, int csidlFolder)
{
LPITEMIDLIST pidl = NULL;
BOOL bRet = FALSE;
if(SUCCEEDED(SHGetSpecialFolderLocation(NULL, csidlFolder, &pidl)))
{
if(SHGetPathFromIDList(pidl, szFolder))
bRet = TRUE;
CoTaskMemFree(pidl);
}
return bRet;
}
BOOL AddMeAsAStartupShortcut(LPCTSTR szLinkTitle, LPCTSTR szDescription,
LPCTSTR szArguments, int IconResourceID)
{
TCHAR szLinkName[MAX_PATH + MAX_PATH + 10];
TCHAR szPathToSelf[MAX_PATH];
if (!GetModuleFileName(NULL, szPathToSelf, MAX_PATH))
return FALSE;
if (FAILED(GetFolderPath(szLinkName, CSIDL_STARTUP)))
return FALSE;
lstrcat(szLinkName, TEXT("\\"));
lstrcat(szLinkName, szLinkTitle);
lstrcat(szLinkName, TEXT(".lnk"));
return SUCCEEDED(CreateMyStartupShortcut(szPathToSelf, szArguments, 0,
IconResourceID != -1 ? szPathToSelf : NULL,
IconResourceID, -1, NULL, szDescription, szLinkName));
}
int main(void)
{
if (!AddMeAsAStartupShortcut(TEXT("My Demo Program"), TEXT("DemoIt"), NULL, -1))
MessageBox(NULL, TEXT("AddMeAsAStartupShortcut Failed to install!!!"), NULL, 0);
else
MessageBox(NULL, TEXT("AddMeAsAStartupShortcut installed successfully!!!"), NULL, 0);
return 0;
}