使用Windows API创建快捷方式.lnk

时间:2020-08-17 02:05:16

标签: c++ windows winapi

使用C ++创建快捷方式时遇到问题。

.lnk文件已创建,但目标文件没有意义。

您能解释一下为什么这段代码没有创建正确的快捷方式吗?有人可以帮我修复我的代码吗?

这是代码

// RepChrome.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "windows.h"
#include "winnls.h"
#include "shobjidl.h"
#include "objbase.h"
#include "objidl.h"
#include "shlguid.h"
#include <shlobj.h>


HRESULT CreateLink(LPCWSTR lpszPathObj1, LPCSTR lpszPathLink, LPCWSTR lpszDesc,LPCWSTR lpszarg) 
{ 
    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(lpszPathObj1); 
        psl->SetArguments(lpszarg);
        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; 
}    

int _tmain(int argc, _TCHAR* argv[])
{
    char sp[MAX_PATH] = { 0 };
    WCHAR p[MAX_PATH]=  { 0 };
    
    WCHAR deskPath[MAX_PATH] = { 0 };
    SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, 0, deskPath);
    sprintf_s( sp,sizeof(deskPath),"%s\\My Program.lnk",deskPath);
    WCHAR path[MAX_PATH] = { 0 };
    SHGetFolderPathW(NULL, CSIDL_PROGRAM_FILESX86, NULL, 0, path);    
    
    swprintf_s( p,sizeof(path),L"%s\\My Program\\start.exe",path);

    CreateLink(p, sp, L"",L""); 

    return 0;
}

1 个答案:

答案 0 :(得分:2)

调用if ($m == 'success') { echo ' Swal.fire({ position: "bottom-end", type: "success", title: "'.$message.'", showConfirmButton: false, timer: 1500, confirmButtonClass: "btn btn-primary", buttonsStyling: false, }) '; } 时,sprintf_s()需要一个%s字符串,但是您却给了它一个char*字符串。另外,您为wchar*sprintf_s()的第二个参数传递了错误的值。

您实际上根本不应该在此代码中使用任何任何 swprintf_s()数据,特别是因为无论如何您只是将其转换为char,因此您应该使用所有{仅{1}}个字符串。将wchar参数更改为wchar,将lpszPathLink缓冲区更改为LPCWSTR,然后将sp更改为WCHAR[]

此外,由于链接所使用的所有值都是sprintf_s(),因此您应直接使用swprintf_s()而不是基于WCHAR的{​​{1}}。 / p>

此外,IShellLinkW要求事先TCHAR被调用,但是在此代码中没有被调用。

尝试以下方法:

IShellLink