IShellLinkインターフェースを使用して、ショートカットファイルを作成します。
※このサンプルを実行する時には、[プロジェクト(P)|オプション(O)...]を開き、[ディレクトリ/条件]タブの中にある[条件定義(C)]に NO_WIN32_LEAN_AND_MEAN を追加してください。
//---------------------------------------------------------------------------
// Unit1.cpp
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include <shlobj.h>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
bool bRet;
bRet = CreateLink("c:\\windows\\デスクトップ\\notepad.lnk","","c:\\windows\\notepad.exe");
if(bRet)
Application->MessageBoxA("成功",Application->Title.c_str(),MB_OK);
else
Application->MessageBoxA("失敗",Application->Title.c_str(),MB_OK);
}
//---------------------------------------------------------------------------
bool TForm1::CreateLink(LPCSTR lpszShortcutFile, LPCSTR lpszDescription,LPCSTR lpszTargetFile)
{
bool bRet = FALSE;
HRESULT hResult;
IShellLink* psl;
CoInitialize(NULL);
hResult = CoCreateInstance(CLSID_ShellLink,
NULL,
CLSCTX_INPROC_SERVER,
IID_IShellLink,
(void **)&psl);
if(SUCCEEDED(hResult)) {
IPersistFile* ppf;
hResult = psl->QueryInterface(IID_IPersistFile,(void **)&ppf);
if (SUCCEEDED(hResult)){
wchar_t wszShortcutFile[MAX_PATH];
hResult = psl->SetPath(lpszTargetFile); // リンクするパス
if (!SUCCEEDED(hResult))
ShowMessage("SetPath failed!");
hResult = psl->SetDescription(lpszDescription); // ディスクリプション
if (!SUCCEEDED(hResult))
ShowMessage("SetDescription failed!");
psl->SetIconLocation(lpszTargetFile, 0); // アイコンを取得するファイル,アイコン番号
//psl->SetWorkingDirectory("C:"); // 作業ディレクトリ
MultiByteToWideChar(CP_ACP, 0, lpszShortcutFile, -1, wszShortcutFile, MAX_PATH);
hResult = ppf->Save(wszShortcutFile, TRUE); // ショートカットの作成
if (!SUCCEEDED(hResult))
ShowMessage("Save failed!");
else
bRet = TRUE;
ppf->Release();
}
psl->Release();
}
CoUninitialize();
return bRet;
}
DownLoad bcbtips025.lzh 4KB(BCB5)