Пример #1
0
bool SetStartOnSystemStartup(bool fAutoStart)
{
    // If the shortcut exists already, remove it for updating
    boost::filesystem::remove(StartupShortcutPath());

    if (fAutoStart)
    {
        CoInitialize(NULL);

        // Get a pointer to the IShellLink interface.
        IShellLink* psl = NULL;
        HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
                                CLSCTX_INPROC_SERVER, IID_IShellLink,
                                reinterpret_cast<void**>(&psl));

        if (SUCCEEDED(hres))
        {
            // Get the current executable path
            TCHAR pszExePath[MAX_PATH];
            GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));

            TCHAR pszArgs[5] = TEXT("-min");

            // Set the path to the shortcut target
            psl->SetPath(pszExePath);
            PathRemoveFileSpec(pszExePath);
            psl->SetWorkingDirectory(pszExePath);
            psl->SetShowCmd(SW_SHOWMINNOACTIVE);
            psl->SetArguments(pszArgs);

            // Query IShellLink for the IPersistFile interface for
            // saving the shortcut in persistent storage.
            IPersistFile* ppf = NULL;
            hres = psl->QueryInterface(IID_IPersistFile,
                                       reinterpret_cast<void**>(&ppf));
            if (SUCCEEDED(hres))
            {
                WCHAR pwsz[MAX_PATH];
                // Ensure that the string is ANSI.
                MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
                // Save the link by calling IPersistFile::Save.
                hres = ppf->Save(pwsz, TRUE);
                ppf->Release();
                psl->Release();
                CoUninitialize();
                return true;
            }
            psl->Release();
        }
        CoUninitialize();
        return false;
    }
    return true;
}
Пример #2
0
void UiPlayer::onFileCreateProjectShortcut(void)
{
    WCHAR shortcutPathBuff[MAX_PATH + 1] = {0};

    OPENFILENAME ofn = {0};
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner   = m_hwnd;
    ofn.lpstrFilter = L"Shortcut (*.lnk)\0*.lnk\0";
    ofn.lpstrTitle  = L"Create Project Shortcut";
    ofn.Flags       = OFN_DONTADDTORECENT | OFN_ENABLESIZING | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
    ofn.lpstrFile   = shortcutPathBuff;
    ofn.nMaxFile    = MAX_PATH;

    if (!GetSaveFileName(&ofn)) return;

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

    if (SUCCEEDED(hres))
    {
        IPersistFile* ppf;

        // args
        string args = m_project.makeCommandLine();

        // Set the path to the shortcut target and add the description.
        psl->SetPath(__wargv[0]);
        wstring wargs;
        wargs.assign(args.begin(), args.end());
        psl->SetArguments(wargs.c_str());
        psl->SetDescription(L"UiPlayer");

        // 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.
            size_t len = wcslen(shortcutPathBuff);
            if (_wcsicmp(shortcutPathBuff + len - 4, L".lnk") != 0)
            {
                wcscat_s(shortcutPathBuff, L".lnk");
            }
            hres = ppf->Save(shortcutPathBuff, TRUE);
            ppf->Release();
        }
        psl->Release();
    }
}
Пример #3
0
BOOL install_util::CreateLnkPath(std::wstring wsSourceFilePath, std::wstring wsDestLnkPath, std::wstring wsArgument, std::wstring wsAppId)
{
  IShellLink *pisl = NULL;
  HRESULT hr = CoCreateInstance(CLSID_ShellLink,
    NULL,
    CLSCTX_INPROC_SERVER,
    IID_IShellLink,
    (void**)&pisl);
  if (FAILED(hr))
  {
    return FALSE;
  }

  pisl->SetPath(wsSourceFilePath.c_str());
  pisl->SetArguments(wsArgument.c_str());
  int nStart = wsSourceFilePath.find_last_of(_T("/\\")); 
  pisl->SetWorkingDirectory(wsSourceFilePath.substr(0,nStart).c_str());
  IPersistFile *plPF = NULL; 
  hr = pisl->QueryInterface(IID_IPersistFile, (void**)&plPF);
  bool shortcut_existed = false;
  if (SUCCEEDED(hr))
  {
    if (PathExists(wsDestLnkPath))
    {
      shortcut_existed = true;
      install_util::DeleteFile(wsDestLnkPath.c_str());
    }
	if (Win7OrLater() && !wsAppId.empty() && wsAppId.length() < 64)
	{
		IPropertyStore *piPS = NULL;
		if (SUCCEEDED(pisl->QueryInterface(IID_IPropertyStore, (void**)&piPS)))
		{
			PROPVARIANT property_value;
			if (SUCCEEDED(InitPropVariantFromString(wsAppId.c_str(), &property_value)))
			{
				if (piPS->SetValue(PKEY_AppUserModel_ID, property_value) == S_OK)
					piPS->Commit();
				PropVariantClear(&property_value);
			}
			piPS->Release();
		}
	}

    hr = plPF->Save(wsDestLnkPath.c_str(), TRUE);
    plPF->Release();
  }

  pisl->Release();
  SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);

  return SUCCEEDED(hr);
}
Пример #4
0
//-----------------------------------------------------------------------------
// Purpose: Creates a shortcut file
//-----------------------------------------------------------------------------
bool CSystem::CreateShortcut(const char *linkFileName, const char *targetPath, const char *arguments, const char *workingDirectory, const char *iconFile)
{
#ifndef _X360
	bool bSuccess = false;
	char temp[MAX_PATH];
	strcpy(temp, linkFileName);

	// make sure it doesn't already exist
	struct _stat statBuf;
	if (_stat(linkFileName, &statBuf) != -1)
		return false;

	// Create the ShellLink object
	IShellLink *psl;
	HRESULT hres = ::CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*) &psl);
	if (SUCCEEDED(hres))
	{
		// Set the target information from the link object
		psl->SetPath(targetPath);
		psl->SetArguments(arguments);
		if (workingDirectory && *workingDirectory)
		{
			psl->SetWorkingDirectory(workingDirectory);
		}
		if (iconFile && *iconFile)
		{
			psl->SetIconLocation(iconFile, 0);
		}

		// Bind the ShellLink object to the Persistent File
		IPersistFile *ppf;
		hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
		if (SUCCEEDED(hres))
		{
			wchar_t wsz[MAX_PATH];
			// Get a UNICODE wide string wsz from the link path
			MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, temp, -1, wsz, MAX_PATH);
			hres = ppf->Save(wsz, TRUE);
			if (SUCCEEDED(hres))
			{
				bSuccess = true;
			}
			ppf->Release();
		}
		psl->Release();
	}
	return bSuccess;
#else
	return false;
#endif
}
// Creates a CLSID_ShellLink to insert into the Tasks section of the Jump List.  This type of Jump
// List item allows the specification of an explicit command line to execute the task.
HRESULT _CreateShellLink(PCWSTR pszArguments, PCWSTR pszTitle, IShellLink **ppsl)
{
    IShellLink *psl;
    HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&psl));
    if (SUCCEEDED(hr))
    {
        // Determine our executable's file path so the task will execute this application
        WCHAR szAppPath[MAX_PATH];
        if (GetModuleFileName(NULL, szAppPath, ARRAYSIZE(szAppPath)))
        {
            hr = psl->SetPath(szAppPath);
            if (SUCCEEDED(hr))
            {
                hr = psl->SetArguments(pszArguments);
                if (SUCCEEDED(hr))
                {
                    // The title property is required on Jump List items provided as an IShellLink
                    // instance.  This value is used as the display name in the Jump List.
                    IPropertyStore *pps;
                    hr = psl->QueryInterface(IID_PPV_ARGS(&pps));
                    if (SUCCEEDED(hr))
                    {
                        PROPVARIANT propvar;
                        hr = InitPropVariantFromString(pszTitle, &propvar);
                        if (SUCCEEDED(hr))
                        {
                            hr = pps->SetValue(PKEY_Title, propvar);
                            if (SUCCEEDED(hr))
                            {
                                hr = pps->Commit();
                                if (SUCCEEDED(hr))
                                {
                                    hr = psl->QueryInterface(IID_PPV_ARGS(ppsl));
                                }
                            }
                            PropVariantClear(&propvar);
                        }
                        pps->Release();
                    }
                }
            }
        }
        else
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
        }
        psl->Release();
    }
    return hr;
}
Пример #6
0
// ショートカット作成
BOOL CreateShortcut ( LPCTSTR pszTargetPath /* ターゲットパス */,
    LPCTSTR pszArguments /* 引数 */,
    LPCTSTR pszWorkPath /* 作業ディレクトリ */,
    int nCmdShow /* ShowWindowの引数 */,
    LPCSTR pszShortcutPath /* ショートカットファイル(*.lnk)のパス */ )
{
    IShellLink *psl = NULL;
    IPersistFile *ppf = NULL;
    enum
    {
        MY_MAX_PATH = 65536
    };
    TCHAR wcLink[ MY_MAX_PATH ]=_T("");

    // IShellLinkインターフェースの作成
    HRESULT result = CoCreateInstance( CLSID_ShellLink, NULL,CLSCTX_INPROC_SERVER, IID_IShellLink, ( void ** ) &psl);
	if(FAILED(result))
    {
		return result;
	}

    // 設定
    psl->SetPath ( pszTargetPath );
    psl->SetArguments ( pszArguments );
    psl->SetWorkingDirectory ( pszWorkPath );
    psl->SetShowCmd ( nCmdShow );

    // IPersistFileインターフェースの作成
    if ( FAILED ( psl->QueryInterface ( IID_IPersistFile, ( void ** ) &ppf ) ) )
    {
        psl->Release ();
        return FALSE;
    }
    
    // lpszLinkをWCHAR型に変換
    MultiByteToWideChar ( CP_ACP, 0, pszShortcutPath, -1, wcLink, MY_MAX_PATH );
    if ( FAILED ( ppf->Save ( wcLink, TRUE ) ) )
    {
        ppf->Release ();
        return FALSE;
    }

	result = ppf->Save((LPCOLESTR)pszShortcutPath,TRUE);
	
    // 解放
    ppf->Release ();
    psl->Release ();

    return TRUE;
}
bool ShellIO::CreateLink(CString fileName, LinkInfo *linkInfo, int flags)
{
	IShellLink *psl;
	IPersistFile *ppf;
	HRESULT hRes;
	bool ret = FALSE;

	hRes = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&psl);
    if(SUCCEEDED(hRes))
    {
        hRes = psl->QueryInterface(IID_IPersistFile, (void**)&ppf);
        if(SUCCEEDED(hRes))
        {
			if((flags & LI_DESCRIPTION) == LI_DESCRIPTION)
			{
				psl->SetDescription(linkInfo->description.GetBuffer());
			}

			if((flags & LI_PATH) == LI_PATH)
			{
				psl->SetPath(linkInfo->path.GetBuffer());
			}

			if((flags & LI_ARGUMENTS) == LI_ARGUMENTS)
			{
				psl->SetArguments(linkInfo->arguments.GetBuffer());
			}

			if((flags & LI_WORKDIRECTORY) == LI_WORKDIRECTORY)
			{
				psl->SetWorkingDirectory(linkInfo->workDirectory.GetBuffer());
			}

			if((flags & LI_ICONLOCATION) == LI_ICONLOCATION)
			{
				psl->SetIconLocation(linkInfo->iconLocation.GetBuffer(), linkInfo->iconIndex);
			}

			hRes = ppf->Save(fileName.GetBuffer(), FALSE);
			ret = SUCCEEDED(hRes);
         
            ppf->Release();
        }

        psl->Release();
	}

	return ret;
}
Пример #8
0
HRESULT CreateShortcut(LPCSTR pszPathObj,LPSTR pszParam,LPSTR pszPath,LPSTR pszPathLink,LPSTR pszDesc)
{
	HRESULT hres; //调用 COM 接口方法之后的返回值
	IShellLink *pShellLink;
	IPersistFile *pPersistFile;
	WCHAR wsz[MAX_PATH]; //UNICODE串, 用来存放快捷方式文件名

	CoInitialize(NULL); //初始化 COM 库
	//创建 COM 对象并获取其实现的接口
	hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,IID_IShellLink,(void **)&pShellLink);
	if(FAILED(hres))
	{
		pShellLink ->Release(); //释放 IShellLink 接口
		CoUninitialize(); //关闭 COM 库, 释放所有 COM 资源
		return FALSE;
	}
	//设置快捷方式的各种属性
	pShellLink->SetPath(pszPathObj); //快捷方式所指的应用程序名
	pShellLink->SetArguments(pszParam); //参数
	pShellLink->SetDescription(pszDesc); //描述
	pShellLink->SetWorkingDirectory(pszPath); //设置工作目录
	//pShellLink->SetIconLocation("C:\\Icon.ico",0); //快捷方式的图标
	//pShellLink->SetHotkey(热键); //启动快捷方式的热键(只能是Ctrl+Alt+_)
	//pShellLink->SetShowCmd(SW_MAXIMIZE); //运行方式(常规窗口,最大化,最小化)
	//查询 IShellLink 接口从而得到 IPersistFile 接口来保存快捷方式
	hres = pShellLink->QueryInterface(IID_IPersistFile,(void **)&pPersistFile);
	if(FAILED(hres))
	{
		pPersistFile ->Release(); //释放 IPersistFile 接口
		pShellLink ->Release(); //释放 IShellLink 接口
		CoUninitialize(); //关闭 COM 库, 释放所有 COM 资源
		return(FALSE);
	}
	//转换 ANSI 串为 UNICODE 串(COM 内部使用 NUICODE)
	MultiByteToWideChar(CP_ACP, 0, pszPathLink, -1, wsz, MAX_PATH);
	//使用 IPersistFile 接口的 Save() 方法保存快捷方式
	hres = pPersistFile ->Save(wsz, TRUE);

	//释放 IPersistFile 接口
	pPersistFile ->Release();
	//释放 IShellLink 接口
	pShellLink ->Release();
	//关闭 COM 库, 释放所有 COM 资源
	CoUninitialize();
	return(hres);
}
Пример #9
0
void AGSWin32::create_shortcut(const char *pathToEXE, const char *workingFolder, const char *arguments, const char *shortcutPath)
{
  IShellLink* pShellLink = NULL;
  HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&pShellLink);

  if ((SUCCEEDED(hr)) && (pShellLink != NULL))
  {
    IPersistFile *pPersistFile = NULL;
    if (FAILED(pShellLink->QueryInterface(IID_IPersistFile, (void**)&pPersistFile)))
    {
      this->DisplayAlert("Unable to add game tasks: QueryInterface for IPersistFile failed");
      pShellLink->Release();
      return;
    }

    // Set the path to the shortcut target and add the description
    if (FAILED(pShellLink->SetPath(pathToEXE)))
    {
      this->DisplayAlert("Unable to add game tasks: SetPath failed");
    }
    else if (FAILED(pShellLink->SetWorkingDirectory(workingFolder)))
    {
      this->DisplayAlert("Unable to add game tasks: SetWorkingDirectory failed");
    }
    else if ((arguments != NULL) && (FAILED(pShellLink->SetArguments(arguments))))
    {
      this->DisplayAlert("Unable to add game tasks: SetArguments failed");
    }
    else
    {
      WCHAR wstrTemp[MAX_PATH] = {0};
      MultiByteToWideChar(CP_ACP, 0, shortcutPath, -1, wstrTemp, MAX_PATH);

      if (FAILED(pPersistFile->Save(wstrTemp, TRUE)))
      {
        this->DisplayAlert("Unable to add game tasks: IPersistFile::Save failed");
      }
    }

    pPersistFile->Release();
  }

  if (pShellLink) pShellLink->Release();
}
Пример #10
0
//-----------------------------------------------------------------------------
// Purpose: sets shortcut (.lnk) information
//-----------------------------------------------------------------------------
bool CSystem::ModifyShortcutTarget(const char *linkFileName, const char *targetPath, const char *arguments, const char *workingDirectory)
{
#ifndef _X360
	bool bSuccess = false;
	char temp[MAX_PATH];
	strcpy(temp, linkFileName);
	strlwr(temp);

	// Create the ShellLink object
	IShellLink *psl;
	HRESULT hres = ::CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*) &psl);
	if (SUCCEEDED(hres))
	{
		IPersistFile *ppf;
		// Bind the ShellLink object to the Persistent File
		hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
		if (SUCCEEDED(hres))
		{
			wchar_t wsz[MAX_PATH];
			// Get a UNICODE wide string wsz from the link path
			MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, temp, -1, wsz, MAX_PATH);
			
			// Read the link into the persistent file
			hres = ppf->Load(wsz, 0);
			
			if (SUCCEEDED(hres))
			{ 
				// Set the target information from the link object
				psl->SetPath(targetPath);
				psl->SetArguments(arguments);
				psl->SetWorkingDirectory(workingDirectory);
				bSuccess = true;
				ppf->Save(wsz, TRUE);
			}
			ppf->Release();
		}
		psl->Release();
	}
	return bSuccess;
#else
	return false;
#endif
}
Пример #11
0
HRESULT create_shortcut(const string& target, const string& arguments, const string& save_as)
{
	IShellLink* sl = NULL;
	HRESULT hres;
	if (SUCCEEDED(hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&sl))))
	{
		sl->SetPath(target.c_str());
		sl->SetArguments(arguments.c_str());
		IPersistFile* pf = NULL;
		if (SUCCEEDED(hres = sl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&pf))))
		{
			wstring name = mbyte_to_wchar(save_as.c_str());
			hres = pf->Save(name.c_str(), true);
			pf->Release();
		}
		sl->Release();
	}
	return hres;
}
Пример #12
0
BOOL CreateShortcut(LPCTSTR linkPath, LPCTSTR targetPath, LPCTSTR comment, LPCTSTR arguments,
                    LPCTSTR workDir, LPCTSTR iconFile, int iconIndex, int showCommand)
{
   // Create a shortcut file
   HRESULT hRes; 
   IShellLink* psl; 

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

      psl->SetPath(targetPath); 
      if (arguments)
         psl->SetArguments(arguments);
      if (workDir)
         psl->SetWorkingDirectory(workDir);
      if (iconFile || iconIndex)
         psl->SetIconLocation(iconFile ? iconFile : targetPath, iconIndex);
      if (comment)
         psl->SetDescription(comment);

      psl->SetShowCmd(showCommand);

      hRes = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); 

      if (SUCCEEDED(hRes))
      {
#ifndef UNICODE
         WCHAR wsz[BUFF_SIZE]; 
         MultiByteToWideChar(CP_ACP, 0, linkPath, -1, wsz, BUFF_SIZE); 

         hRes = ppf->Save(wsz, TRUE);
#else
         hRes = ppf->Save(linkPath, TRUE);
#endif
         ppf->Release(); 
      } 
      psl->Release(); 
   } 
   return TRUE; 
} 
Пример #13
0
HRESULT CreateLink(LPCSTR linkPath, LPCWSTR targetPath, LPCWSTR args)
{
	HRESULT hres;

	if (!called_coinit)
	{
		hres = CoInitialize(NULL);
		called_coinit = true;

		if (!SUCCEEDED(hres))
		{
			wxLogError(_("Failed to initialize COM. Error 0x%08X"), hres);
			return hres;
		}
	}


	IShellLink* link;
	hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&link);

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

		link->SetPath(targetPath); 
		link->SetArguments(args);

		hres = link->QueryInterface(IID_IPersistFile, (LPVOID*)&persistFile);
		if (SUCCEEDED(hres))
		{
			WCHAR wstr[MAX_PATH];

			MultiByteToWideChar(CP_ACP, 0, linkPath, -1, wstr, MAX_PATH);

			hres = persistFile->Save(wstr, TRUE);
			persistFile->Release();
		}
		link->Release();
	}
	return hres;
}
Пример #14
0
HRESULT CreateLink(LPCSTR lpszPathLink, LPCSTR lpszPathObj, LPCSTR lpszDesc, LPCSTR lpszArgs) 
{ 
	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; 
 
		// Set the path to the shortcut target and add the description. 
		psl->SetPath(lpszPathObj); 
		if(lpszArgs) {
			psl->SetArguments(lpszArgs);
		}
		psl->SetDescription(lpszDesc); 
 
		// Query IShellLink for the IPersistFile interface, used for saving the 
		// shortcut in persistent storage. 
		hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); 
 
		if (SUCCEEDED(hres)) 
		{ 
			WCHAR wsz[MAX_PATH]; 
 
			// Ensure that the string is Unicode. 
			MultiByteToWideChar(CP_ACP, 0, lpszPathLink, -1, wsz, MAX_PATH); 
			
			// Add code here to check return value from MultiByteWideChar 
			// for success.
 
			// Save the link by calling IPersistFile::Save. 
			hres = ppf->Save(wsz, TRUE); 
			ppf->Release(); 
		} 
		psl->Release(); 
	} 
	return hres; 
}
Пример #15
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;
	}
Пример #16
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();
  }
}
Пример #17
0
HRESULT ShellFunctions::CreateShortcut(LPCSTR pszShortcutFile,LPCSTR pszLink,LPCSTR pszDesc,LPCSTR pszParams)
{
	HRESULT hres;
	IShellLink* psl;
	hres=CoCreateInstance(CLSID_ShellLink,NULL,CLSCTX_INPROC_SERVER,IID_IShellLink,(void**)&psl);
	if (SUCCEEDED(hres))
	{
		IPersistFile* ppf;
		hres=psl->QueryInterface(IID_IPersistFile,(void**)&ppf);
		if (SUCCEEDED(hres))
		{
			hres=psl->SetPath(pszLink);
			if (SUCCEEDED(hres))
			{
				LONG_PTR nIndex=LastCharIndex(pszLink,'\\');
				if (nIndex>=0)
				{
					char szWDir[MAX_PATH];
					MemCopy(szWDir,pszLink,nIndex);
					szWDir[nIndex]='\0';
					psl->SetWorkingDirectory(szWDir);
				}

				if (pszDesc!=NULL)
					psl->SetDescription(pszDesc);
				if (pszParams!=NULL)
					psl->SetArguments(pszParams);
				
				WCHAR wsz[MAX_PATH];
				MultiByteToWideChar(CP_ACP,0,pszShortcutFile,-1,wsz,MAX_PATH);
				hres=ppf->Save(wsz,TRUE);    
			}
			ppf->Release(); 
		}
		psl->Release();
	}
	return hres;
}
bool UIDesktopServices::createMachineShortcut(const QString & /* strSrcFile */, const QString &strDstPath, const QString &strName, const QUuid &uUuid)
{
    IShellLink *pShl = NULL;
    IPersistFile *pPPF = NULL;
    const QString strVBox = QDir::toNativeSeparators(QCoreApplication::applicationDirPath() + "/" + VBOX_GUI_VMRUNNER_IMAGE);
    QFileInfo fi(strVBox);
    QString strVBoxDir = QDir::toNativeSeparators(fi.absolutePath());
    HRESULT rc = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)(&pShl));
    if (FAILED(rc))
        return false;
    do
    {
        rc = pShl->SetPath(strVBox.utf16());
        if (FAILED(rc))
            break;
        rc = pShl->SetWorkingDirectory(strVBoxDir.utf16());
        if (FAILED(rc))
            break;
        QString strArgs = QString("--comment \"%1\" --startvm \"%2\"").arg(strName).arg(uUuid.toString());
        rc = pShl->SetArguments(strArgs.utf16());
        if (FAILED(rc))
            break;
        QString strDesc = QString("Starts the VirtualBox machine %1").arg(strName);
        rc = pShl->SetDescription(strDesc.utf16());
        if (FAILED(rc))
            break;
        rc = pShl->QueryInterface(IID_IPersistFile, (void**)&pPPF);
        if (FAILED(rc))
            break;
        QString strLink = QString("%1\\%2.lnk").arg(strDstPath).arg(strName);
        rc = pPPF->Save(strLink.utf16(), TRUE);
    } while(0);
    if (pPPF)
        pPPF->Release();
    if (pShl)
        pShl->Release();
    return SUCCEEDED(rc);
}
Пример #19
0
// @pymethod |PyIShellLink|SetArguments|Sets the command-line arguments associated with a shell link object.
PyObject *PyIShellLink::SetArguments(PyObject *self, PyObject *args)
{
	IShellLink *pISL = GetI(self);
	if ( pISL == NULL )
		return NULL;
	PyObject *obArgs;
	// @pyparm str|args||The new arguments.
	if ( !PyArg_ParseTuple(args, "O:SetArguments", &obArgs) )
		return NULL;
	TCHAR *pszArgs;
	if (!PyWinObject_AsTCHAR(obArgs, &pszArgs))
		return NULL;
	HRESULT hr;
	PY_INTERFACE_PRECALL;
	hr = pISL->SetArguments( pszArgs );
	PY_INTERFACE_POSTCALL;
	PyWinObject_FreeTCHAR(pszArgs);

	if ( FAILED(hr) )
		return OleSetOleError(hr);
	Py_INCREF(Py_None);
	return Py_None;

}
Пример #20
0
BOOL Shortcut_Create (LPTSTR pszTarget, LPCTSTR pszSource, LPTSTR pszDesc, LPTSTR pszArgs)
{
   IShellLink *psl;
   HRESULT rc = CoCreateInstance (CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl);
   if (SUCCEEDED (rc))
      {
      IPersistFile *ppf;
      rc = psl->QueryInterface (IID_IPersistFile, (void **)&ppf);
      if (SUCCEEDED (rc))
         { 
         rc = psl->SetPath (pszSource);
         if (SUCCEEDED (rc))
            {
            rc = psl->SetDescription (pszDesc ? pszDesc : pszSource);
            if (SUCCEEDED (rc))
               {
               if ( pszArgs )
                   rc = psl->SetArguments (pszArgs);
                   if (SUCCEEDED (rc))
                   {
#ifdef UNICODE
                   rc = ppf->Save (pszTarget, TRUE);
#else
                   WORD wsz[ MAX_PATH ];
                   MultiByteToWideChar (CP_ACP, 0, pszTarget, -1, (LPWSTR)wsz, MAX_PATH);
                   rc = ppf->Save ((LPCOLESTR)wsz, TRUE);
#endif
                   }
               }
            }
         ppf->Release ();
         }
      psl->Release ();
      }
   return SUCCEEDED(rc) ? TRUE : FALSE;
} 
Пример #21
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;
}
Пример #22
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;
}
Пример #23
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);
}
Пример #24
0
void TaskList::addToRecentList(QString name, QString user, QString host, int port) {
	if (! bIsWin7)
		return;

	HRESULT hr;
	IShellLink *link = NULL;
	IPropertyStore *ps = NULL;
	PROPVARIANT pt;

	hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, __uuidof(IShellLink), reinterpret_cast<void **>(&link));
	if (!link || FAILED(hr))
		return;

	QUrl url;
	url.setScheme(QLatin1String("mumble"));
	url.setUserName(user);
	url.setHost(host);
	url.setPort(port);

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
	QUrlQuery query;
	query.addQueryItem(QLatin1String("title"), name);
	query.addQueryItem(QLatin1String("version"), QLatin1String("1.2.0"));
	url.setQuery(query);
#else
	url.addQueryItem(QLatin1String("title"), name);
	url.addQueryItem(QLatin1String("version"), QLatin1String("1.2.0"));
#endif

	QSettings settings(QLatin1String("HKEY_CLASSES_ROOT"), QSettings::NativeFormat);

	QString app = settings.value(QLatin1String("mumble/DefaultIcon/.")).toString();
	if (app.isEmpty() || ! QFileInfo(app).exists())
		app = QCoreApplication::applicationFilePath();

	link->SetPath(app.toStdWString().c_str());
	link->SetArguments(QString::fromLatin1(url.toEncoded()).toStdWString().c_str());

	hr = link->QueryInterface(__uuidof(IPropertyStore), reinterpret_cast<void **>(&ps));
	if (FAILED(hr)) {
		qFatal("TaskList: Failed to get property store");
		goto cleanup;
	}

	InitPropVariantFromString(name.toStdWString().c_str(), &pt);
	hr = ps->SetValue(PKEY_Title, pt);
	PropVariantClear(&pt);

	if (FAILED(hr)) {
		qFatal("TaskList: Failed to set title");
		goto cleanup;
	}

	hr = ps->Commit();
	if (FAILED(hr)) {
		qFatal("TaskList: Failed commit");
		goto cleanup;
	}

	SHAddToRecentDocs(SHARD_LINK, link);

cleanup:
	if (ps)
		ps->Release();
	if (link)
		link->Release();
}
Пример #25
0
HRESULT ShellFunctions::CreateShortcut(LPCWSTR pszShortcutFile,LPCWSTR pszLink,LPCWSTR pszDesc,LPCWSTR pszParams)
{
	HRESULT hres;
	
	if (IsUnicodeSystem())
	{
		IShellLinkW* psl;
		hres=CoCreateInstance(CLSID_ShellLink,NULL,CLSCTX_INPROC_SERVER,IID_IShellLinkW,(void**)&psl);
		if (SUCCEEDED(hres))
		{
			IPersistFile* ppf;
			hres=psl->QueryInterface(IID_IPersistFile,(void**)&ppf);
			if (SUCCEEDED(hres))
			{
				hres=psl->SetPath(pszLink);
				if (SUCCEEDED(hres))
				{
					
					int nIndex=LastCharIndex(pszLink,L'\\');
					if (nIndex>=0)
					{
						WCHAR szWDir[MAX_PATH];
						MemCopyW(szWDir,pszLink,nIndex);
						szWDir[nIndex]='\0';
						psl->SetWorkingDirectory(szWDir);
					}
										
					if (pszDesc!=NULL)
						psl->SetDescription(pszDesc);
					if (pszParams!=NULL)
						psl->SetArguments(pszParams);
					
					hres=ppf->Save(pszShortcutFile,TRUE);    
				}
				ppf->Release(); 
			}
			psl->Release();
		}
	}
	else
	{
		IShellLink* psl;
		hres=CoCreateInstance(CLSID_ShellLink,NULL,CLSCTX_INPROC_SERVER,IID_IShellLink,(void**)&psl);
		if (SUCCEEDED(hres))
		{
			IPersistFile* ppf;
			hres=psl->QueryInterface(IID_IPersistFile,(void**)&ppf);
			if (SUCCEEDED(hres))
			{
				hres=psl->SetPath(W2A(pszLink));
				if (SUCCEEDED(hres))
				{
					LONG_PTR nIndex=LastCharIndex(pszLink,L'\\');
					if (nIndex>=0)
					{
						char szWDir[MAX_PATH];
						WideCharToMultiByte(CP_ACP,0,pszLink,(int)nIndex,szWDir,MAX_PATH,0,0);
						szWDir[nIndex]='\0';
						psl->SetWorkingDirectory(szWDir);
					}

					if (pszDesc!=NULL)
						psl->SetDescription(W2A(pszDesc));
					if (pszParams!=NULL)
						psl->SetArguments(W2A(pszParams));

					hres=ppf->Save(pszShortcutFile,TRUE);    
				}
				ppf->Release(); 
			}
			psl->Release();
		}
	}
	return hres;
}
Пример #26
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;
}
Пример #27
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;
}
Пример #28
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;
}
Пример #29
0
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPWSTR cmdParamarg, int cmdShow) {
	openLog();

	_oldWndExceptionFilter = SetUnhandledExceptionFilter(_exceptionFilter);
//	CAPIHook apiHook("kernel32.dll", "SetUnhandledExceptionFilter", (PROC)RedirectedSetUnhandledExceptionFilter);

	writeLog(L"Updaters started..");

	LPWSTR *args;
	int argsCount;

	bool needupdate = false, autostart = false, debug = false, writeprotected = false, startintray = false, testmode = false;
	args = CommandLineToArgvW(GetCommandLine(), &argsCount);
	if (args) {
		for (int i = 1; i < argsCount; ++i) {
			if (equal(args[i], L"-update")) {
				needupdate = true;
			} else if (equal(args[i], L"-autostart")) {
				autostart = true;
			} else if (equal(args[i], L"-debug")) {
				debug = _debug = true;
				openLog();
			} else if (equal(args[i], L"-startintray")) {
				startintray = true;
			} else if (equal(args[i], L"-testmode")) {
				testmode = true;
			} else if (equal(args[i], L"-writeprotected") && ++i < argsCount) {
				writeprotected = true;
				updateTo = args[i];
				for (int i = 0, l = updateTo.size(); i < l; ++i) {
					if (updateTo[i] == L'/') {
						updateTo[i] = L'\\';
					}
				}
			}
		}
		if (needupdate) writeLog(L"Need to update!");
		if (autostart) writeLog(L"From autostart!");
		if (writeprotected) writeLog(L"Write Protected folder!");

		exeName = args[0];
		writeLog(L"Exe name is: " + exeName);
		if (exeName.size() > 11) {
			if (equal(exeName.substr(exeName.size() - 11), L"Updater.exe")) {
				exeDir = exeName.substr(0, exeName.size() - 11);
				writeLog(L"Exe dir is: " + exeDir);
				if (!writeprotected) {
					updateTo = exeDir;
				}
				writeLog(L"Update to: " + updateTo);
				if (needupdate && update()) {
					updateRegistry();
				}
				if (writeprotected) { // if we can't clear all tupdates\ready (Updater.exe is there) - clear only version
					if (DeleteFile(L"tupdates\\temp\\tdata\\version") || DeleteFile(L"tupdates\\ready\\tdata\\version")) {
						writeLog(L"Version file deleted!");
					} else {
						writeLog(L"Error: could not delete version file");
					}
				}
			} else {
				writeLog(L"Error: bad exe name!");
			}
		} else {
			writeLog(L"Error: short exe name!");
		}
		LocalFree(args);
	} else {
		writeLog(L"Error: No command line arguments!");
	}

	wstring targs;
	if (autostart) targs += L" -autostart";
	if (debug) targs += L" -debug";
	if (startintray) targs += L" -startintray";
	if (testmode) targs += L" -testmode";

	bool executed = false;
	if (writeprotected) { // run un-elevated
		writeLog(L"Trying to run un-elevated by temp.lnk");

		HRESULT hres = CoInitialize(0);
		if (SUCCEEDED(hres)) {
			IShellLink* psl;
			HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
			if (SUCCEEDED(hres)) {
				IPersistFile* ppf;

				wstring exe = updateTo + L"Telegram.exe", dir = updateTo;
				psl->SetArguments((targs.size() ? targs.substr(1) : targs).c_str());
				psl->SetPath(exe.c_str());
				psl->SetWorkingDirectory(dir.c_str());
				psl->SetDescription(L"");

				hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);

				if (SUCCEEDED(hres)) {
					wstring lnk = L"tupdates\\temp\\temp.lnk";
					hres = ppf->Save(lnk.c_str(), TRUE);
					if (!SUCCEEDED(hres)) {
						lnk = L"tupdates\\ready\\temp.lnk"; // old
						hres = ppf->Save(lnk.c_str(), TRUE);
					}
					ppf->Release();

					if (SUCCEEDED(hres)) {
						writeLog(L"Executing un-elevated through link..");
						ShellExecute(0, 0, L"explorer.exe", lnk.c_str(), 0, SW_SHOWNORMAL);
						executed = true;
					} else {
						writeLog(L"Error: ppf->Save failed");
					}
				} else {
					writeLog(L"Error: Could not create interface IID_IPersistFile");
				}
				psl->Release();
			} else {
				writeLog(L"Error: could not create instance of IID_IShellLink");
			}
			CoUninitialize();
		} else {
			writeLog(L"Error: Could not initialize COM");
		}
	}
	if (!executed) {
		ShellExecute(0, 0, (updateTo + L"Telegram.exe").c_str(), (L"-noupdate" + targs).c_str(), 0, SW_SHOWNORMAL);
	}

	writeLog(L"Executed Telegram.exe, closing log and quiting..");
	closeLog();

	return 0;
}
Пример #30
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;
}