Raspuns: Folosesc interfata IShellLink pentru a crea un shell link apoi IPersistFile pentru a-l salva intr-un fisier cu extensia .lnk.
Code: Select all
#include <Shobjidl.h>
#include <atlbase.h>
#define TEST_HRESULT(hr) if(FAILED(hr)) return hr
HRESULT _CreateShortcutW(
LPCWSTR pszTergetPath, // path and file name for the target of shell link
LPCWSTR pszShortcutPath, // path and file name of shell link
LPCWSTR pszArgs = NULL, // command-line arguments
WORD wHotkey = 0, // keyboard shortcut (hot key)
LPCWSTR pszWorkingDir = NULL, // working directory
int nShowCmd = SW_SHOWNORMAL, // show command
LPCWSTR pszDescription = NULL, // description
LPCWSTR pszIconFile = NULL, // file containing the icon
int nIconIndex = 0 // icon index
)
{
CComPtr<IShellLinkW> pShellLink;
TEST_HRESULT(pShellLink.CoCreateInstance(CLSID_ShellLink));
TEST_HRESULT(pShellLink->SetPath(pszTergetPath));
TEST_HRESULT(pShellLink->SetArguments(pszArgs));
TEST_HRESULT(pShellLink->SetHotkey(wHotkey));
TEST_HRESULT(pShellLink->SetWorkingDirectory(pszWorkingDir));
TEST_HRESULT(pShellLink->SetShowCmd(nShowCmd));
TEST_HRESULT(pShellLink->SetDescription(pszDescription));
TEST_HRESULT(pShellLink->SetIconLocation(pszIconFile, nIconIndex));
CComQIPtr<IPersistFile> pFile = pShellLink;
TEST_HRESULT(pFile->Save(pszShortcutPath, TRUE));
return S_OK;
}
Code: Select all
#include <atlstr.h>
#include <shlobj.h>
int main()
{
::CoInitialize(NULL); // Initialize COM library
CStringW strWindowsPath, strSystemPath, strDesktopPath;
::SHGetSpecialFolderPathW(NULL, strWindowsPath.GetBuffer(MAX_PATH), CSIDL_WINDOWS, FALSE);
strWindowsPath.ReleaseBuffer();
::SHGetSpecialFolderPathW(NULL, strSystemPath.GetBuffer(MAX_PATH), CSIDL_SYSTEM, FALSE);
strSystemPath.ReleaseBuffer();
::SHGetSpecialFolderPathW(NULL, strDesktopPath.GetBuffer(MAX_PATH), CSIDL_DESKTOPDIRECTORY, FALSE);
strDesktopPath.ReleaseBuffer();
CStringW strTergetPath = strWindowsPath + L"\\explorer.exe";
CStringW strShortcutPath = strDesktopPath + L"\\Explorer System32.lnk";
CStringW strArgs = CStringW(L"/root,") + strSystemPath;
WORD wHotkey = MAKEWORD('S', HOTKEYF_CONTROL|HOTKEYF_ALT); // Ctrl+Alt+S
LPCWSTR pszWorkingDir = NULL; // no specified working directory
int nShowCmd = SW_SHOWMAXIMIZED; // show application window in maximized state
LPCWSTR pszDescription = L"Show system folder in Windows Explorer";
CStringW strIconFile = strSystemPath + L"\\shell32.dll";
int nIconIndex = 15;
HRESULT hr = _CreateShortcutW(strTergetPath, strShortcutPath, strArgs, wHotkey,
pszWorkingDir, nShowCmd, pszDescription, strIconFile, nIconIndex);
if(FAILED(hr))
{
CStringW strMessage;
strMessage.Format(L"_CreateShortcutW failed\nHRESULT: 0x%08X", hr);
::MessageBoxW(NULL, strMessage, L"Demo create shorcut", MB_ICONERROR);
}
::CoUninitialize();
return 0;
}
- Windows Dev Center: Shell Links
<< Back to MFC index