Пример #1
0
	HRESULT CreateLink(
			const char *link_fn, const char *target_cmd, const char *target_args,
			const char *work_path, const char *icon_fn
		)
	{
		HRESULT hres;
		IShellLink* psl;

		// Get a pointer to the IShellLink interface. It is assumed that CoInitialize
		// has already been called.
		hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
		if(SUCCEEDED(hres)) {
			IPersistFile* ppf;

			LINK_MACRO_EXPAND(WCHAR_T_DEC);
			LINK_MACRO_EXPAND(WCHAR_T_CONV_VLA);

			// Set the path to the shortcut target and add the description.
			psl->SetPath(target_cmd_w);
			psl->SetArguments(target_args_w);
			psl->SetWorkingDirectory(work_path_w);
			psl->SetIconLocation(icon_fn_w, 0);

			// Query IShellLink for the IPersistFile interface, used for saving the
			// shortcut in persistent storage.
			hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);

			if(SUCCEEDED(hres)) {
				// Save the link by calling IPersistFile::Save.
				hres = ppf->Save(link_fn_w, FALSE);
				if(FAILED(hres)) {
					hres = GetLastError();
				}
				ppf->Release();
			}
			psl->Release();
			LINK_MACRO_EXPAND(WCHAR_T_FREE);
		}
		return hres;
	}
Пример #2
0
void CreateShortCut(HWND hwnd, LPTSTR pszShortcutFile, LPTSTR pszIconFile, int iconindex, LPTSTR pszExe, LPTSTR pszArg, LPTSTR workingdir)
{
  HRESULT hres;
  IShellLink* psl;
  static int initcom;

  if (!initcom) CoInitialize(0);
  initcom=1;

  hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                            IID_IShellLink, (void **) &psl);
  if (SUCCEEDED(hres))
  {
    IPersistFile* ppf;

    hres = psl->QueryInterface(IID_IPersistFile, (void **) &ppf); // OLE 2!  Yay! --YO
    if (SUCCEEDED(hres))
    {
      WORD wsz[MAX_PATH];
      MultiByteToWideChar(CP_ACP, 0, pszShortcutFile, -1, wsz, MAX_PATH);

       hres = psl->SetPath(pszExe);
       psl->SetWorkingDirectory(workingdir);
       if (pszIconFile) psl->SetIconLocation(pszIconFile,iconindex);
       if (pszArg) 
       {
         psl->SetArguments(pszArg);
       }

       if (SUCCEEDED(hres))
       {
		   ppf->Save(wsz,TRUE);
       }
      ppf->Release();
    }
    psl->Release();
  }
}
Пример #3
0
HRESULT LINK(PTSTR ptzCmd)
{
	// Parse Shortcut,Target,Param,IconPath,IconIndex
	PTSTR ptzTarget = UStrChr(ptzCmd, CC_SEP);
	if (ptzTarget == NULL)
	{
		return ERROR_PATH_NOT_FOUND;
	}

	INT iIcon = 0;
	PTSTR ptzIcon = NULL;

	*ptzTarget++ = 0;
	PTSTR ptzParam = UStrChr(ptzTarget, CC_SEP);
	if (ptzParam)
	{
		*ptzParam++ = 0;
		ptzIcon = UStrChr(ptzParam, CC_SEP);
		if (ptzIcon)
		{
			*ptzIcon++ = 0;
			PTSTR ptzIndex = UStrChr(ptzIcon, CC_SEP);
			if (ptzIndex)
			{
				*ptzIndex++ = 0;
				iIcon = UStrToInt(ptzIndex);
			}
		}
	}

	// Search target
	if (*ptzCmd == '*')
	{
		ptzCmd++;
	}
	else
	{
		TCHAR tzTarget[MAX_PATH];
		if (SearchPath(NULL, ptzTarget, NULL, MAX_PATH, tzTarget, NULL))
		{
			ptzTarget = tzTarget;
		}
		else if (!UDirExist(ptzTarget))
		{
			return ERROR_PATH_NOT_FOUND;
		}
	}

	// Create shortcut
	IShellLink *pLink;
	CoInitialize(NULL);
	HRESULT hResult = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (PVOID *) &pLink);
	if (hResult == S_OK)
	{
		IPersistFile *pFile;
		hResult = pLink->QueryInterface(IID_IPersistFile, (PVOID *) &pFile);
		if (hResult == S_OK)
		{
			if (*ptzCmd == '!')
			{
				ptzCmd++;
				hResult = pLink->SetShowCmd(SW_SHOWMINIMIZED);
			}

			// Shortcut settings
			hResult = pLink->SetPath(ptzTarget);
			hResult = pLink->SetArguments(ptzParam);
			hResult = pLink->SetIconLocation(ptzIcon, iIcon);
			if (UPathSplit(ptzTarget) != ptzTarget)
			{
				hResult = pLink->SetWorkingDirectory(ptzTarget);
			}

			// Save link
			WCHAR wzLink[MAX_PATH];
			if (UStrCmpI(ptzCmd + UStrLen(ptzCmd) - 4, TEXT(".LNK")))
			{
				UStrCat(ptzCmd, TEXT(".LNK"));
			}
			UStrToWStr(wzLink, ptzCmd, MAX_PATH);
			UDirCreate(ptzCmd);
			hResult = pFile->Save(wzLink, FALSE);

			pFile->Release();
		}
		pLink->Release();
	}

	CoUninitialize();
	return hResult;
}
Пример #4
0
BOOL CInstall::CreateShellLink(LPCSTR description, LPCSTR program,
                               LPCSTR arguments, LPCSTR icon, int nIconIndex)
{
    HRESULT hres;
    IShellLink* psl;
    CHAR szLink[MAXSTR];
    strcpy(szLink, m_szPrograms);
    strcat(szLink, "\\");
    strcat(szLink, m_szTargetGroup);
    strcat(szLink, "\\");
    strcat(szLink, description);
    strcat(szLink, ".LNK");
    AddMessage("Adding shell link\n   ");
    AddMessage(szLink);
    AddMessage("\n");

    // Ensure string is UNICODE.
    WCHAR wsz[MAX_PATH];
    MultiByteToWideChar(CP_ACP, 0, szLink, -1, wsz, MAX_PATH);

    // Save old shell link

    // Get a pointer to the IShellLink interface.
    hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                            IID_IShellLink, (void **)&psl);
    if (SUCCEEDED(hres))    {
        IPersistFile* ppf;
        // Query IShellLink for the IPersistFile interface.
        hres = psl->QueryInterface(IID_IPersistFile, (void **)&ppf);
        if (SUCCEEDED(hres))       {
            // Load the shell link.
            hres = ppf->Load(wsz, STGM_READ);
            if (SUCCEEDED(hres)) {
                // Resolve the link.
                hres = psl->Resolve(HWND_DESKTOP, SLR_ANY_MATCH);
                if (SUCCEEDED(hres)) {
                    // found it, so save details
                    CHAR szTemp[MAXSTR];
                    WIN32_FIND_DATA wfd;
                    int i;


                    fprintf(m_fLogOld, "Name=%s\n", szLink);
                    hres = psl->GetPath(szTemp, MAXSTR, (WIN32_FIND_DATA *)&wfd,
                                        SLGP_SHORTPATH );
                    if (SUCCEEDED(hres))
                        fprintf(m_fLogOld, "Path=%s\n", szTemp);
                    hres = psl->GetDescription(szTemp, MAXSTR);
                    if (SUCCEEDED(hres))
                        fprintf(m_fLogOld, "Description=%s\n", szTemp);
                    hres = psl->GetArguments(szTemp, MAXSTR);
                    if (SUCCEEDED(hres) && (szTemp[0] != '\0'))
                        fprintf(m_fLogOld, "Arguments=%s\n", szTemp);
                    hres = psl->GetWorkingDirectory(szTemp, MAXSTR);
                    if (SUCCEEDED(hres) && (szTemp[0] != '\0'))
                        fprintf(m_fLogOld, "Directory=%s\n", szTemp);
                    hres = psl->GetIconLocation(szTemp, MAXSTR, &i);
                    if (SUCCEEDED(hres) && (szTemp[0] != '\0')) {
                        fprintf(m_fLogOld, "IconLocation=%s\n", szTemp);
                        fprintf(m_fLogOld, "IconIndex=%d\n", i);
                    }
                    fprintf(m_fLogOld, "\n");
                }
            }
            // Release pointer to IPersistFile.
            ppf->Release();
        }
        // Release pointer to IShellLink.
        psl->Release();
    }


    // Save new shell link

    // Get a pointer to the IShellLink interface.
    hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                            IID_IShellLink, (void **)&psl);
    if (SUCCEEDED(hres))    {
        IPersistFile* ppf;
        // Query IShellLink for the IPersistFile interface for
        // saving the shell link in persistent storage.
        hres = psl->QueryInterface(IID_IPersistFile, (void **)&ppf);
        if (SUCCEEDED(hres)) {
            fprintf(m_fLogNew, "Name=%s\n", szLink);

            // Set the path to the shell link target.
            hres = psl->SetPath(program);
            if (!SUCCEEDED(hres))
                AddMessage("SetPath failed!");
            fprintf(m_fLogNew, "Path=%s\n", program);
            // Set the description of the shell link.
            hres = psl->SetDescription(description);
            if (!SUCCEEDED(hres))
                AddMessage("SetDescription failed!");
            fprintf(m_fLogNew, "Description=%s\n", description);
            if (arguments != (LPCSTR)NULL) {
                // Set the arguments of the shell link target.
                hres = psl->SetArguments(arguments);
                if (!SUCCEEDED(hres))
                    AddMessage("SetArguments failed!");
                fprintf(m_fLogNew, "Arguments=%s\n", arguments);
            }
            if (icon != (LPCSTR)NULL) {
                // Set the arguments of the shell link target.
                hres = psl->SetIconLocation(icon, nIconIndex);
                if (!SUCCEEDED(hres))
                    AddMessage("SetIconLocation failed!");
                fprintf(m_fLogNew, "IconLocation=%s\n", icon);
                fprintf(m_fLogNew, "IconIndex=%d\n", nIconIndex);
            }

            // Save the link via the IPersistFile::Save method.
            hres = ppf->Save(wsz, TRUE);
            // Release pointer to IPersistFile.
            ppf->Release();
        }
        // Release pointer to IShellLink.
        psl->Release();
        fprintf(m_fLogNew, "\n");
    }

    return (hres == 0);
}
Пример #5
0
//---------------------------------------------------------------------------
//	◎함수명 : CreateShortcut
//	◎함수설명 : 바로가기를 만든다
//	◎인자
//	strPathLink : 생성될 바로가기 파일의 경로와 이름
//  strObjPath : 실행할 오브젝트
//  strArgs : 실행시 인자
//	strIcon : 사용될 아이콘 리소스 지정 (EXE, ICO 등)
//	strDesc : 마우스가 올라갈때 나타나는 툴팁
//	◎반환값 : 성공시 TRUE, 실패시 FALSE
//---------------------------------------------------------------------------
BOOL COutputDialog::CreateShortcut(LPCTSTR strShortcutPath, LPCTSTR strObjPath, LPCTSTR strArgs, LPCTSTR strWorkingDir, LPCTSTR strIconPath, LPCTSTR strDesc)
{
	BOOL bRetVal = FALSE;

	HRESULT hres = 0;
	IShellLink* psl = NULL;
	IPersistFile* ppf = NULL;
	
	//CString strMyPath = strPathLink;
	
	try
	{
		CString strTmpDir = _T("");

		if(NULL == strShortcutPath || NULL == strObjPath
		   || _T('\0') == strShortcutPath[0] || _T('\0') == strObjPath[0]) throw _T("파일 위치 지정이 잘못되었습니다.");

		if(NULL == strIconPath || _T('\0') == strIconPath) strIconPath = strObjPath;
		if(NULL == strWorkingDir || _T('\0') == strWorkingDir)
		{
			strTmpDir = strObjPath;
			int nIdx = strTmpDir.ReverseFind('\\');
			if(nIdx > 0) strTmpDir = strTmpDir.Left(nIdx);
			else strTmpDir = _T("");
		}
		else
		{
			strTmpDir = strWorkingDir;
		}
		
		::CoInitialize(NULL);
		hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*) &psl);
		if (FAILED(hres)) throw _T("ShellLink 객체를 생성할 수 없습니다.");

		psl->SetPath(strObjPath);
		psl->SetIconLocation(strIconPath, 0);
		psl->SetWorkingDirectory(strTmpDir);
		if(strArgs && strArgs[0]) psl->SetArguments(strArgs);
		if(strDesc && strDesc[0]) psl->SetDescription(strDesc);

		hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
		if (FAILED(hres)) throw _T("IPersistFile 인터페이스를 얻어올 수 없습니다.");

		// 확장자를 검사하여 붙여줌
		CString strMyPath = strShortcutPath;
		if(strMyPath.Right(4).CompareNoCase(_T(".lnk"))) strMyPath += _T(".lnk");

#ifdef UNICODE
		LPCWSTR wsz = (LPCWSTR)strMyPath;
#else
		wchar_t wsz[MAX_PATH] = {0,};
		MyMultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)strMyPath, -1, wsz, MAX_PATH);
#endif

		// 생성
		DeleteFile(wsz);
		hres = ppf->Save(wsz, TRUE);		
		if (hres != S_OK ) throw _T("IPersistFile->Save() 에러");

		bRetVal = TRUE;

	}
	catch (LPCTSTR cszErr)
	{
		cszErr = cszErr;
		bRetVal = FALSE;
	}

	if(ppf) ppf->Release();
	if(psl) psl->Release();

	return bRetVal;
}
Пример #6
0
//---------------------------------------------------------------------------
IShellLink * __fastcall CreateDesktopShortCut(const UnicodeString & Name,
  const UnicodeString &File, const UnicodeString & Params, const UnicodeString & Description,
  int SpecialFolder, int IconIndex, bool Return)
{
  IShellLink* pLink = NULL;

  if (SpecialFolder < 0)
  {
    SpecialFolder = CSIDL_DESKTOPDIRECTORY;
  }

  try
  {
    if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
         IID_IShellLink, (void **) &pLink)))
    {
      try
      {
        pLink->SetPath(File.c_str());
        pLink->SetDescription(Description.c_str());
        pLink->SetArguments(Params.c_str());
        pLink->SetShowCmd(SW_SHOW);
        // Explicitly setting icon file,
        // without this icons are not shown at least in Windows 7 jumplist
        pLink->SetIconLocation(File.c_str(), IconIndex);

        IPersistFile* pPersistFile;
        if (!Return &&
            SUCCEEDED(pLink->QueryInterface(IID_IPersistFile, (void **)&pPersistFile)))
        {
          try
          {
            LPMALLOC      ShellMalloc;
            LPITEMIDLIST  DesktopPidl;
            wchar_t DesktopDir[MAX_PATH];

            OleCheck(SHGetMalloc(&ShellMalloc));

            try
            {
              OleCheck(SHGetSpecialFolderLocation(NULL, SpecialFolder, &DesktopPidl));

              OleCheck(SHGetPathFromIDList(DesktopPidl, DesktopDir));
            }
            __finally
            {
              ShellMalloc->Free(DesktopPidl);
              ShellMalloc->Release();
            }

            WideString strShortCutLocation(DesktopDir);
            // Name can contain even path (e.g. to create quick launch icon)
            strShortCutLocation += UnicodeString(L"\\") + Name + L".lnk";
            OleCheck(pPersistFile->Save(strShortCutLocation.c_bstr(), TRUE));
          }
          __finally
          {
            pPersistFile->Release();
          }
        }

        // this is necessary for Windows 7 taskbar jump list links
        IPropertyStore * PropertyStore;
        if (SUCCEEDED(pLink->QueryInterface(IID_IPropertyStore, (void**)&PropertyStore)))
        {
          PROPVARIANT Prop;
          Prop.vt = VT_LPWSTR;
          Prop.pwszVal = Name.c_str();
          PropertyStore->SetValue(PKEY_Title, Prop);
          PropertyStore->Commit();
          PropertyStore->Release();
        }
      }
      catch(...)
      {
        pLink->Release();
        throw;
      }

      if (!Return)
      {
        pLink->Release();
        pLink = NULL;
      }
    }
  }
  catch(Exception & E)
  {
    throw ExtException(&E, LoadStr(CREATE_SHORTCUT_ERROR));
  }

  return pLink;
}
Пример #7
0
static PyObject *CreateShortcut(PyObject *self, PyObject *args)
{
    Py_UNICODE *path; /* path and filename */
    Py_UNICODE *description;
    Py_UNICODE *filename;

    Py_UNICODE *arguments = NULL;
    Py_UNICODE *iconpath = NULL;
    int iconindex = 0;
    Py_UNICODE *workdir = NULL;

    IShellLink *pShellLink = NULL;
    IPersistFile *pPersistFile = NULL;

    HRESULT hres;

    hres = CoInitialize(NULL);
    if (FAILED(hres)) {
        PyErr_Format(PyExc_OSError,
                       "CoInitialize failed, error 0x%x", hres);
        goto error;
    }

    if (!PyArg_ParseTuple(args, "uuu|uuui",
                          &path, &description, &filename,
                          &arguments, &workdir, &iconpath, &iconindex)) {
        return NULL;
    }

    hres = CoCreateInstance(CLSID_ShellLink, NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_IShellLink,
                          (void **)&pShellLink);
    if (FAILED(hres)) {
        PyErr_Format(PyExc_OSError,
                       "CoCreateInstance failed, error 0x%x", hres);
        goto error;
    }

    hres = pShellLink->QueryInterface(IID_IPersistFile, (void**)&pPersistFile);
    if (FAILED(hres)) {
        PyErr_Format(PyExc_OSError,
                       "QueryInterface(IPersistFile) error 0x%x", hres);
        goto error;
    }


    hres = pShellLink->SetPath(path);
    if (FAILED(hres)) {
        PyErr_Format(PyExc_OSError,
                       "SetPath() failed, error 0x%x", hres);
        goto error;
    }

    hres = pShellLink->SetDescription(description);
    if (FAILED(hres)) {
        PyErr_Format(PyExc_OSError,
                       "SetDescription() failed, error 0x%x", hres);
        goto error;
    }

    if (arguments) {
        hres = pShellLink->SetArguments(arguments);
        if (FAILED(hres)) {
                PyErr_Format(PyExc_OSError,
                               "SetArguments() error 0x%x", hres);
                goto error;
        }
    }

    if (iconpath) {
        hres = pShellLink->SetIconLocation(iconpath, iconindex);
        if (FAILED(hres)) {
                PyErr_Format(PyExc_OSError,
                               "SetIconLocation() error 0x%x", hres);
                goto error;
        }
    }

    if (workdir) {
        hres = pShellLink->SetWorkingDirectory(workdir);
        if (FAILED(hres)) {
                PyErr_Format(PyExc_OSError,
                               "SetWorkingDirectory() error 0x%x", hres);
                goto error;
        }
    }

    hres = pPersistFile->Save(filename, TRUE);
    if (FAILED(hres)) {
        PyObject *fn = PyUnicode_FromUnicode(filename, wcslen(filename));
        if (fn) {
            PyObject *msg = PyUnicode_FromFormat(
                        "Failed to create shortcut '%U' - error 0x%x",
                        fn, hres);
            if (msg) {
                PyErr_SetObject(PyExc_OSError, msg);
                Py_DECREF(msg);
            }
            Py_DECREF(fn);
        }
        goto error;
    }

    pPersistFile->Release();
    pShellLink->Release();

    CoUninitialize();
    Py_RETURN_NONE;

  error:
    if (pPersistFile) {
        pPersistFile->Release();
    }
    if (pShellLink) {
        pShellLink->Release();
    }

    CoUninitialize();
    return NULL;
}
Пример #8
0
// Creates a shortcut in the startup folder.
void SetStartupOptions() {
	// Required for Win95
	CoInitialize(NULL);
	
	// Create the COM server
	IShellLink *pShellLink = NULL;
	HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL,
			CLSCTX_INPROC_SERVER, IID_IShellLink,
			reinterpret_cast<LPVOID*>(&pShellLink));
	if (FAILED(hr))
		return;
	
	TCHAR szPath[MAX_PATH] = {0};
	GetModuleFileName(NULL, szPath, sizeof(szPath));
	GetShortPathName(szPath, szPath, sizeof(szPath));
	
	// Set attributes
	pShellLink->SetPath(szPath);
	pShellLink->SetDescription(SZ_APPNAME);
	pShellLink->SetHotkey(0);
	pShellLink->SetIconLocation(szPath, 0);
	
	// Get the IPersistFile interface to save
	IPersistFile *pPF = NULL;
	hr = pShellLink->QueryInterface(IID_IPersistFile, reinterpret_cast<LPVOID*>(&pPF));
	
	if (FAILED(hr)) {
		pShellLink->Release();
		return;
	}
	
	LPMALLOC pMalloc;
	if (SUCCEEDED(SHGetMalloc(&pMalloc))) {
		LPITEMIDLIST pidl;
		SHGetSpecialFolderLocation(NULL, CSIDL_STARTUP, &pidl);
		SHGetPathFromIDList(pidl, szPath);
		pMalloc->Free(pidl);
		pMalloc->Release();
	}
	
	// Create a .lnk file
	TCHAR szLinkFile[MAX_PATH] = {0};
	wsprintf(szLinkFile, "%s.lnk", SZ_APPNAME);
	
	if (szPath[lstrlen(szPath) - 1] != '\\')
		lstrcat(szPath, "\\");
	lstrcat(szPath, szLinkFile);
	
	if (g_bStartWithWindows) {
		// Save Unicode LNK file
		WCHAR wszLinkFile[MAX_PATH] = {0};
		MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szPath, -1, wszLinkFile, MAX_PATH);
		hr = pPF->Save(wszLinkFile, TRUE);
		if (FAILED(hr))
			ShowError(IDS_STARTUP_ERR, MB_ICONHAND);
	} else {
		DeleteFile(szPath);
	}
	
	// Clean up
	pPF->Release();
	pShellLink->Release();
	CoUninitialize();
}
Пример #9
0
BOOL CShortcut::CreateShortCut(const CString &LnkTarget,
                               const CString &LnkName, UINT SpecialFolder,
                               const CString &LnkDescription,
                               const CString &IconLocation, UINT IconIndex)
{
  CFile cfFull;
  CString sExePath, sExe, sSpecialFolder;

  wchar_t *chTmp = sExePath.GetBuffer(MAX_PATH);

  GetModuleFileName(NULL, chTmp, MAX_PATH);

  sExePath.ReleaseBuffer();

  // Find the Special Folder:
  if (!GetSpecialFolder(SpecialFolder, sSpecialFolder))
    return FALSE;

  sSpecialFolder += LnkName + L"." + L"lnk";

  if (LnkTarget == L"_this") {
    cfFull.SetFilePath(sExePath);
    sExe = cfFull.GetFileName();
    sExe.Delete(sExe.Find(L".") + 1, 3);
  } else {
    sExePath = LnkTarget;
  }

  // Create the ShortCut:
  CoInitialize(NULL);
  BOOL bRet = FALSE;
  IShellLink* psl;

  if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink,
                                 NULL,
                                 CLSCTX_INPROC_SERVER,
                                 IID_IShellLink,
                                 (LPVOID*) &psl))) {
    IPersistFile* ppf;

    psl->SetPath(sExePath);
    psl->SetDescription(LnkDescription);

    if (!m_sCmdArg.IsEmpty())
      psl->SetArguments(m_sCmdArg);

    if (SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf))) {
      /* Call IShellLink::SetIconLocation with the file containing
         the icon and the index of the icon */
      if (!IconLocation.IsEmpty()) {
        HRESULT hr = psl->SetIconLocation(IconLocation, IconIndex);
#ifdef _DEBUG
        if (FAILED(hr))
          pws_os::Trace(L"IconLocation not changed!\n");
#endif
      }

      if (SUCCEEDED(ppf->Save(sSpecialFolder, TRUE)))
      {
        bRet = TRUE;
      }
      ppf->Release();
    }
    psl->Release();
  } 

  pws_os::Trace(bRet ? L"Lnk Written!\n" :
               L"Lnk NOT Written! CreateShortCut(...) failed!\n");
  return bRet;
}
Пример #10
0
void CNotifierApp::CreateShortcut()
{
	HRESULT hr;
	IShellLink * lpShellLink = NULL;
	IPersistFile * lpPersistFile = NULL;
	WCHAR szStartupPath[MAX_PATH];
	wstring szModuleFilename(GetModuleFileNameEx());
	wstring szModulePath(GetDirname(szModuleFilename));

	if (!SHGetSpecialFolderPath(NULL, szStartupPath, CSIDL_STARTUP , FALSE))
	{
		return;
	}

	wstring szTargetPath(szStartupPath);

	szTargetPath += L"\\Google Wave Notifier.lnk";

	hr = CoCreateInstance(
		CLSID_ShellLink,
		NULL,
		CLSCTX_INPROC_SERVER,
		IID_IShellLink,
		reinterpret_cast<void**>(&lpShellLink)
	);

	if (!SUCCEEDED(hr))
	{
		goto __end;
	}

	ASSERT(lpShellLink != NULL);

	lpShellLink->SetIconLocation(szModuleFilename.c_str(), 0);
	lpShellLink->SetPath(szModuleFilename.c_str());
	lpShellLink->SetWorkingDirectory(szModulePath.c_str());

	hr = lpShellLink->QueryInterface(
		IID_IPersistFile,
		reinterpret_cast<void**>(&lpPersistFile)
	);

	if (!SUCCEEDED(hr))
	{
		goto __end;
	}

	ASSERT(lpPersistFile != NULL);

	// hr not checked because we can't do anything about it.

	lpPersistFile->Save(szTargetPath.c_str(), FALSE);

__end:
	if (lpPersistFile != NULL)
	{
		lpPersistFile->Release();
	}

	if (lpShellLink != NULL)
	{
		lpShellLink->Release();
	}
}
Пример #11
0
int installShortcut(const WORD *shortcutPath, const unsigned short *shortcutNameU,
                    const unsigned short *descriptionU, const unsigned short *pathU,
                    const unsigned short *argumentsU, const unsigned short *workingDirectoryU,
                    const unsigned short *iconPathU) {
    char *shortcutName = javawsWideCharToMBCS(shortcutNameU);
    char *description = javawsWideCharToMBCS(descriptionU);
    char *path = javawsWideCharToMBCS(pathU);
    char *arguments = javawsWideCharToMBCS(argumentsU);
    char *workingDirectory = javawsWideCharToMBCS(workingDirectoryU);
    char *iconPath = javawsWideCharToMBCS(iconPathU);

    // Initialize COM, stash the result to know if we need to call
    // CoUnintialize
    HRESULT comStart = CoInitialize(NULL);

    HRESULT tempResult;
    IShellLink *shell;

    int retValue = 0;

    // Find IShellLink interface.
    tempResult = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                                  IID_IShellLink, (void **)&shell);

    if (SUCCEEDED(tempResult)) {
        IPersistFile* persistFile;

        // Query IShellLink for the IPersistFile interface for
        // saving the shell link in persistent storage.
        tempResult = shell->QueryInterface(IID_IPersistFile,
                                           (void **)&persistFile);
        if (SUCCEEDED(tempResult)) {

            // Set the path to the shell link target.
            tempResult = shell->SetPath(path);

            if (!SUCCEEDED(tempResult)) {
                // Couldn't set the path
                retValue = -2;
            }

            // Set the description of the shell link.
            // fix for 4499382
            // make sure description length is less than MAX_PATH
            // else truncate the string before setting description
            if (retValue == 0 && description != NULL &&
                    strlen(description) < MAX_PATH &&
                    !SUCCEEDED(shell->SetDescription(description))) {
                retValue = -3;
            } else {
                char *desc = (char*)malloc(sizeof(char)*MAX_PATH);
                desc = strncpy(desc, description, MAX_PATH - 1);
                if (!SUCCEEDED(shell->SetDescription(desc))) {
                    retValue = -3;
                }
            }

            // Set the arguments
            if (retValue == 0 && arguments != NULL &&
                    !(SUCCEEDED(shell->SetArguments(arguments)))) {
                retValue = -4;
            }

            // Working directory
            if (retValue == 0 && workingDirectory != NULL &&
                    !(SUCCEEDED(shell->SetWorkingDirectory(workingDirectory)))) {
                retValue = -5;
            }

            // Sets the icon location, default to an icon index of 0.
            if (retValue == 0 && iconPath != NULL &&
                    !(SUCCEEDED(shell->SetIconLocation(iconPath, 0)))) {
                retValue = -6;
            }
            // PENDING: if iconPath == null, should install a link to
            // the default icon!

            // Defaults to a normal window.
            if (retValue == 0) {
                shell->SetShowCmd(SW_NORMAL);

                // Save the link via the IPersistFile::Save method.
                if (!SUCCEEDED(persistFile->Save(shortcutPath, TRUE))) {
                    retValue = -7;
                }
            }
            // Release pointer to IPersistFile.
            persistFile->Release();
        }
        else {
            // No persist file
            retValue = -8;
        }
        // Release pointer to IShellLink.
        shell->Release();
    }
    else {
        // No shell!
        retValue = -9;
    }
    if (comStart == S_OK) {
        CoUninitialize();
    }
    free(shortcutName);
    free(description);
    free(path);
    free(arguments);
    free(workingDirectory);
    free(iconPath);
    return retValue;
}