- 1 year ago
Creating a Windows shortcut (shell link) in C++
Comment
1 / 1
To create a Windows shortcut (also known as shell link) in C++, you can use the COM interface IShellLink
provided by the Windows Shell. Here is an example of how to create a shortcut:
cpp#include <windows.h>
#include <shobjidl.h> // For IShellLink, IPersistFile
int main()
{
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (SUCCEEDED(hr))
{
// Create a new shell link object
IShellLink* psl;
hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
if (SUCCEEDED(hr))
{
// Set the path to the target executable
psl->SetPath(L"C:\\Windows\\notepad.exe");
// Set the arguments for the target executable (optional)
psl->SetArguments(L"C:\\Windows\\system.ini");
// Set the working directory for the target executable (optional)
psl->SetWorkingDirectory(L"C:\\Windows\\");
// Query the IPersistFile interface to save the shell link
IPersistFile* ppf;
hr = psl->QueryInterface(IID_IPersistFile, (void**)&ppf);
if (SUCCEEDED(hr))
{
// Save the shell link to a file
hr = ppf->Save(L"C:\\Users\\John\\Desktop\\Notepad.lnk", TRUE);
ppf->Release();
}
psl->Release();
}
CoUninitialize();
}
return 0;
}
This code creates a new shell link object, sets the target executable, arguments, and working directory, queries the IPersistFile
interface to save the shell link, and saves the shell link to a file.
Note that to use this code, you need to link against the ole32
library by adding the following line to your linker options:
diff-l ole32