ショートカットの作成には、IShellLinkインターフェイスで行います。IShellLinkインターフェイスは、CoCreateInstance()関数で取得します。 IShellLinkのSetPath()メソッドでリンク先を設定します。IShellLinkインターフェイスは保存用のメソッドは持っていないので、 QueryInterface()関数でIPersistFileインタフェイスを取得して、Saveメソッドで保存を行います。
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <string>
#include <shlobj.h>
/*
ショートカットの作成
*/
HRESULT CreateShortCut
(
std::wstring strShortCutNamePath // 作成するショートカットのパス(.lnk)
, std::wstring strLinkPath // リンク先パス
)
{
// 処理結果
HRESULT hResult = S_OK;
// IShellLink
IShellLink* pSellLink = NULL;
// IPersistFile
IPersistFile* pPersistFile = NULL;
/*
IShellLinkの取得
*/
hResult = CoCreateInstance( CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&pSellLink );
if ( !SUCCEEDED( hResult ) ) {
// エラー
goto err;
}
/*
IPersistFileの取得
*/
hResult = pSellLink->QueryInterface( IID_IPersistFile, (void**)&pPersistFile );
if ( !SUCCEEDED( hResult ) ) {
// エラー
goto err;
}
// リンク先パスの設定
hResult = pSellLink->SetPath( strLinkPath.c_str() );
if ( !SUCCEEDED( hResult ) ) {
// エラー
goto err;
}
// ショートカットの保存
hResult = pPersistFile->Save( strShortCutNamePath.c_str(), TRUE );
if ( !SUCCEEDED( hResult ) ) {
// エラー
goto err;
}
err:
// IPersistFileの解放
if ( NULL != pPersistFile ) {
pPersistFile->Release();
}
// IShellLinkの解放
if ( NULL != pSellLink ) {
pSellLink->Release();
}
// 処理結果を返す
return( hResult );
}
/*
ショートカットリンクを作成する
*/
int _tmain
(
int argc
, _TCHAR* argv[]
)
{
HRESULT hResult = S_OK;
/*
std::wcoutのロケールを設定
これを設定するだけで、std::wcoutで日本語が表示される
ようになります。
*/
std::wcout.imbue( std::locale( "", std::locale::ctype ) );
// COM初期化
::CoInitialize( NULL );
/*
デスクトップのパスを取得
*/
std::wstring strDesktopPath;
{
TCHAR waFolderPath[ MAX_PATH ];
// デスクトップのパスを取得
SHGetSpecialFolderPath( NULL, waFolderPath, CSIDL_DESKTOP, 0 );
// wstring変換
strDesktopPath = waFolderPath;
}
/*
My Documentsのパスを取得
*/
std::wstring strMyDocumentPath;
{
TCHAR waFolderPath[ MAX_PATH ];
// My Documentのパスを取得
SHGetSpecialFolderPath( NULL, waFolderPath, CSIDL_PERSONAL, 0 );
// wstring変換
strMyDocumentPath = waFolderPath;
}
/*
ショートカットを作成
(デスクトップへマイドキュメントへのショートカットリンクを作成します。)
*/
hResult = CreateShortCut(
strDesktopPath + L"¥¥まいどきゅめんとへのショートカット.lnk" // ショートカット作成パス
, strMyDocumentPath // リンク先パス
);
if ( S_OK == hResult ) {
// 成功
std::wcout << L"ショートカットの作成に成功しました。" << std::endl;
}
else {
// 失敗
std::wcout << L"ショートカットの作成に失敗しました。" << std::endl;
}
// COM終了
::CoUninitialize();
// 正常終了
return( 0 );
}
ショートカットの作成に成功しました。