Beispiel #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;
}
Beispiel #2
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);
}
//-----------------------------------------------------------------------------
// 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
}
Beispiel #4
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;
}
Beispiel #6
0
HRESULT CWipeFree::CreateIt(LPCTSTR pszShortcutFile, LPTSTR pszLink)
{
    HRESULT		hres;
    IShellLink* psl;

    // Get a pointer to the IShellLink interface.
	CoInitialize(NULL);
    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))
       {   
         //WORD wsz[MAX_PATH];

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

         if (!SUCCEEDED(hres))
           AfxMessageBox(_T("SetPath failed!"));

         // Set the description of the shell link.
		 hres = psl->SetWorkingDirectory(m_szCurDir);

         if (!SUCCEEDED(hres))
           AfxMessageBox(_T("SetDescription failed!"));

         //// Ensure string is ANSI.
         //MultiByteToWideChar(CP_ACP, 0, pszLink, -1, wsz, MAX_PATH);

         // Save the link via the IPersistFile::Save method.
         //hres = ppf->Save(wsz, TRUE);
		 hres = ppf->Save(pszLink, TRUE);

         // Release pointer to IPersistFile.
         ppf->Release();
       }
       // Release pointer to IShellLink.
       psl->Release();
    }
	CoUninitialize();
    return hres;
}
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);
}
Beispiel #8
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();
}
int create_shortcut(string src_path, string dst_path, string working_directory)
{
#ifdef _WIN32
	CoInitialize(NULL);
	IShellLink* pShellLink = NULL;
	HRESULT hres;
	hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_ALL,
		IID_IShellLink, (void**)&pShellLink);

	if (SUCCEEDED(hres))
	{
		pShellLink->SetPath(src_path.c_str());
		pShellLink->SetDescription("");
		pShellLink->SetIconLocation(src_path.c_str(), 0);
		pShellLink->SetWorkingDirectory(working_directory.c_str());

		IPersistFile *pPersistFile;
		hres = pShellLink->QueryInterface(IID_IPersistFile, (void**)&pPersistFile);

		if (SUCCEEDED(hres))
		{
			hres = pPersistFile->Save(CA2W(dst_path.c_str()), TRUE);
			pPersistFile->Release();
		}
		else
		{
			console_log("Error 2");
			return 2;
		}
		pShellLink->Release();
	}
	else
	{
		console_log("Error 1");
		return 1;
	}
	
#elif __APPLE__
	//todo: port to OSX
#endif

	return 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
}
Beispiel #11
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; 
} 
Beispiel #12
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;
	}
Beispiel #13
0
//
//	创建快捷方式
//
bool	Shortcut_Create(const char* szPath, const char* szWorkingPath, const char* szLink) {
    HRESULT hres ;
    IShellLink * psl ;
    IPersistFile* ppf ;
    WCHAR wsz[MAX_PATH]= {L""};
    ////初始化COM
    CoInitialize (NULL);
    //创建一个IShellLink实例
    hres = CoCreateInstance( CLSID_ShellLink, NULL,CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl);
    if( FAILED( hres)) {
        CoUninitialize ();
        return false ;
    }

    //设置目标应用程序
    psl->SetPath( szPath);
    psl->SetWorkingDirectory(szWorkingPath);

    //从IShellLink获取其IPersistFile接口
    //用于保存快捷方式的数据文件 (*.lnk)
    hres = psl->QueryInterface(IID_IPersistFile, (void**)&ppf) ;
    if( FAILED( hres)) {
        CoUninitialize ();
        return false ;
    }

    // 确保数据文件名为ANSI格式
    MultiByteToWideChar( CP_ACP, 0, szLink, -1, wsz, MAX_PATH) ;

    //调用IPersistFile::Save
    //保存快捷方式的数据文件 (*.lnk)
    hres = ppf->Save(wsz, STGM_READWRITE);
    //释放IPersistFile和IShellLink接口
    ppf->Release() ;
    psl->Release() ;
    CoUninitialize();

    return true;
}
Beispiel #14
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();
  }
}
Beispiel #15
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;
}
Beispiel #16
0
	bool createLink()
	{
		if (!SUCCEEDED(CoInitialize(NULL))) return false;
		IShellLink *pisl;
		if (!SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL,
			CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&pisl)))
		{
			CoUninitialize();
			return false;
		}
		IPersistFile* pIPF;
		std::string tmpStr = XFile::getCurrentExeFileFullPath();
		pisl->SetPath(tmpStr.c_str());
		pisl->SetWorkingDirectory(XFile::getWorkPath().c_str());
		if (!SUCCEEDED(pisl->QueryInterface(IID_IPersistFile, (void**)&pIPF)))
		{
			pisl->Release();
			CoUninitialize();
			return false;
		}
		if (tmpStr.size() >= 3)
		{
			memcpy(&tmpStr[tmpStr.size() - 3], &"lnk", 3);
			//tmpStr[tmpStr.size() - 3] = 'l';
			//tmpStr[tmpStr.size() - 2] = 'n';
			//tmpStr[tmpStr.size() - 1] = 'k';
		}
		else
			return false;

		wchar_t wsz[MAX_PATH]; // 定义Unicode字符串 
		MultiByteToWideChar(CP_ACP, 0, tmpStr.c_str(), -1, wsz, MAX_PATH);
		pIPF->Save(wsz, FALSE);
		pIPF->Release();
		pisl->Release();
		CoUninitialize();
		return true;
	}
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);
}
// @pymethod |PyIShellLink|SetWorkingDirectory|Description of SetWorkingDirectory.
PyObject *PyIShellLink::SetWorkingDirectory(PyObject *self, PyObject *args)
{
	IShellLink *pISL = GetI(self);
	if ( pISL == NULL )
		return NULL;
	PyObject *obName;
	if ( !PyArg_ParseTuple(args, "O:SetWorkingDirectory", &obName) )
		return NULL;
	TCHAR *pszName;
	if (!PyWinObject_AsTCHAR(obName, &pszName))
		return NULL;
	HRESULT hr;
	PY_INTERFACE_PRECALL;
	hr = pISL->SetWorkingDirectory( pszName );
	PY_INTERFACE_POSTCALL;
	PyWinObject_FreeTCHAR(pszName);

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

}
Beispiel #19
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;
}
//---------------------------------------------------------------------------
//	◎함수명 : 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;
}
Beispiel #21
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;
}
Beispiel #22
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;
}
Beispiel #23
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;
}
Beispiel #24
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();
	}
}
bool QFSFileEngine::link(const QString &newName)
{
#if !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
#if !defined(QT_NO_LIBRARY)
    bool ret = false;

    QString linkName = newName;
    //### assume that they add .lnk

    IShellLink *psl;
    bool neededCoInit = false;

    HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl);

    if (hres == CO_E_NOTINITIALIZED) { // COM was not initialized
        neededCoInit = true;
        CoInitialize(NULL);
        hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl);
    }

    if (SUCCEEDED(hres)) {
        hres = psl->SetPath((wchar_t *)fileName(AbsoluteName).replace(QLatin1Char('/'), QLatin1Char('\\')).utf16());
        if (SUCCEEDED(hres)) {
            hres = psl->SetWorkingDirectory((wchar_t *)fileName(AbsolutePathName).replace(QLatin1Char('/'), QLatin1Char('\\')).utf16());
            if (SUCCEEDED(hres)) {
                IPersistFile *ppf;
                hres = psl->QueryInterface(IID_IPersistFile, (void **)&ppf);
                if (SUCCEEDED(hres)) {
                    hres = ppf->Save((wchar_t*)linkName.utf16(), TRUE);
                    if (SUCCEEDED(hres))
                         ret = true;
                    ppf->Release();
                }
            }
        }
        psl->Release();
    }
    if (!ret)
        setError(QFile::RenameError, qt_error_string());

    if (neededCoInit)
        CoUninitialize();

    return ret;
#else
    Q_UNUSED(newName);
    return false;
#endif // QT_NO_LIBRARY
#elif defined(Q_OS_WINCE) && !defined(QT_NO_WINCE_SHELLSDK)
    QString linkName = newName;
    linkName.replace(QLatin1Char('/'), QLatin1Char('\\'));
    if (!linkName.endsWith(QLatin1String(".lnk")))
        linkName += QLatin1String(".lnk");
    QString orgName = fileName(AbsoluteName).replace(QLatin1Char('/'), QLatin1Char('\\'));
    // Need to append on our own
    orgName.prepend(QLatin1Char('"'));
    orgName.append(QLatin1Char('"'));
    bool ret = SUCCEEDED(SHCreateShortcut((wchar_t*)linkName.utf16(), (wchar_t*)orgName.utf16()));
    if (!ret)
        setError(QFile::RenameError, qt_error_string());
    return ret;
#else // Q_OS_WINCE && !QT_NO_WINCE_SHELLSDK
    Q_UNUSED(newName);
    Q_UNIMPLEMENTED();
    return false;
#endif // Q_OS_WINRT
}
Beispiel #26
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;
}
HRESULT CreateLink(LPCSTR lpszPathObj, LPCSTR lpszPathLink, LPCSTR _fileName, LPCSTR lpszDesc, LPCSTR args = NULL) 
{ 
    HRESULT hres; 
    IShellLink* psl; 
 
    // Get a pointer to the IShellLink interface. 
    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. 

		char exePath[1024];
		strcpy( exePath, lpszPathObj );
		char *fileName = strrchr( exePath, '\\' ) + 1;
		exePath[ strlen(exePath) - strlen(fileName) ] = '\0';

		WCHAR objectPath[1024];
		WCHAR objectDir[1024];
		MultiByteToWideChar(CP_ACP, 0, lpszPathObj, -1, objectPath, MAX_PATH); 
		MultiByteToWideChar(CP_ACP, 0, exePath, -1, objectDir, MAX_PATH); 

        psl->SetPath(objectPath); 
        psl->SetDescription((LPCWSTR)lpszDesc);
		psl->SetWorkingDirectory(objectDir);
		if( args != NULL )
		{
			WCHAR wArgs[256];
			MultiByteToWideChar(CP_ACP, 0,args, -1, wArgs, MAX_PATH); 
			psl->SetArguments( wArgs );
		}
 
        // Query IShellLink for the IPersistFile interface for saving the 
        // shortcut in persistent storage. 
        hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); 
 
        if (SUCCEEDED(hres)) 
        { 
            WCHAR wsz[MAX_PATH]; 
			WCHAR fullFilePath[MAX_PATH];
 
            // Ensure that the string is Unicode. 
            MultiByteToWideChar(CP_ACP, 0, lpszPathLink, -1, wsz, MAX_PATH); 
			MultiByteToWideChar(CP_ACP, 0, _fileName, -1, fullFilePath, MAX_PATH); 
			
            // Add code here to check return value from MultiByteWideChar 
            // for success.
 
            // Save the link by calling IPersistFile::Save. 
			SHCreateDirectoryEx(NULL, wsz, NULL );
			hres = ppf->Save(fullFilePath, TRUE); 
            ppf->Release(); 
        }
		else
		{
            MessageBox(NULL, L"Failed to create shortcut", L"Darwinia: Vista Edition", MB_OK );
		}
        psl->Release(); 
    } 
	else
	{
		MessageBox(NULL, L"Failed to create shortcut", L"Darwinia: Vista Edition", MB_OK );
	}
    return hres; 
}