1 #include<windows.h> 2 #include <string> 3 #include <shellapi.h> 4 #include <shlobj.h> 5 #pragma comment(lib, "shell32.lib") 6 using namespace std; 7 #ifdef _UNICODE 8 typedef wstring tstring; 9 #else 10 typedef string tstring; 11 #endif 12 /* 13 //獲取相關系統路徑 14 HRESULT SHGetSpecialFolderLocation( 15 HWND hwndOwner, int nFolder, PIDLIST_ABSOLUTE *ppidl 16 ); 17 18 第一個參數表示所有者窗口句柄,一般傳入NULL就可以了。 19 第二個參數要示是一個整數id,決定哪個目錄是待查找目錄, 它的取值可能是 20 CSIDL_BITBUCKET 回收站 21 CSIDL_CONTROLS 控制面板 22 CSIDL_DESKTOP Windows桌面desktop; 23 24 CSIDL_DESKTOPDIRECTORY desktop的目錄; 25 CSIDL_DRIVES 我的電腦 26 CSIDL_FONTS 字體目錄 27 CSIDL_NETHOOD 網上鄰居 28 CSIDL_NETWORK 網上鄰居virtual folder 29 30 CSIDL_PERSONAL 我的文檔 31 CSIDL_PRINTERS 打印機 32 CSIDL_PROGRAMS 程序組 33 CSIDL_RECENT 最近打開文檔 34 CSIDL_SENDTO 發送到菜單項 35 CSIDL_STARTMENU 快速啟動菜單 36 CSIDL_STARTUP 啟動目錄 37 CSIDL_TEMPLATES 臨時文檔 38 第三個參數表示一個條目標識符列表指針,可以傳入一個LPITEMIDLIST類型變量,再從這個變量中得到表示路徑的字符串。使用完后,要用void CoTaskMemFree(void * pv)來釋放資源。 39 */ 40 41 42 43 //封裝的創建快捷方式API 44 // szStartAppPath : 點擊后啟動的程序 45 // szAddCmdLine : 傳給main函數的lpCmdLine 46 // szDestLnkPath : 快捷方式的保存路徑 47 // szIconPath : 快捷方式顯示的圖標 48 bool CreateLinkFile(LPCTSTR szStartAppPath, LPCTSTR szAddCmdLine, LPCOLESTR szDestLnkPath, LPCTSTR szIconPath) 49 { 50 HRESULT hr = CoInitialize(NULL); 51 if (SUCCEEDED(hr)) 52 { 53 IShellLink *pShellLink; 54 hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&pShellLink); 55 if (SUCCEEDED(hr)) 56 { 57 pShellLink->SetPath(szStartAppPath); 58 tstring strTmp = szStartAppPath; 59 int nStart = strTmp.find_last_of(TEXT("/\\")); 60 pShellLink->SetWorkingDirectory(strTmp.substr(0, nStart).c_str()); 61 pShellLink->SetArguments(szAddCmdLine); 62 if (szIconPath) 63 { 64 pShellLink->SetIconLocation(szIconPath, 0); 65 } 66 IPersistFile* pPersistFile; 67 hr = pShellLink->QueryInterface(IID_IPersistFile, (void**)&pPersistFile); 68 if (SUCCEEDED(hr)) 69 { 70 hr = pPersistFile->Save(( szDestLnkPath), FALSE); 71 if (SUCCEEDED(hr)) 72 { 73 return true; 74 } 75 pPersistFile->Release(); 76 } 77 pShellLink->Release(); 78 } 79 CoUninitialize(); 80 } 81 return false; 82 } 83 //百度的string轉換wstring 84 std::wstring s2ws(const std::string& s) 85 { 86 int len; 87 int slength = (int)s.length() + 1; 88 len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 89 wchar_t* buf = new wchar_t[len]; 90 MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); 91 std::wstring r(buf); 92 delete[] buf; 93 return r; 94 } 95 96 int main() 97 { 98 99 LPITEMIDLIST lp; 100 SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY, &lp); 101 char lstr[100]=""; 102 SHGetPathFromIDList(lp,lstr); 103 string s = lstr; 104 s += "\\CMGPAUSE.lnk"; 105 CreateLinkFile("cmd.exe", "pause", s2ws(s).c_str(),"1.bmp"); 106 107 }