0

如何从 Windows 快捷方式(.lnk 文件)以编程方式启动应用程序?

我尝试使用 API ShellExecute,它似乎工作。有什么警告吗?

谢谢你。

这是我当前代码的片段:

#include <windows.h>

#include <map>
#include <string>
#include <iostream>

int main( int, char** )
{
   std::map< int, std::wstring > errors;
   errors[0]                      = L"The operating system is out of memory or resources.";
   errors[ERROR_FILE_NOT_FOUND]   = L"The specified file was not found."; 
   errors[ERROR_PATH_NOT_FOUND]   = L"The specified path was not found."; 
   errors[ERROR_BAD_FORMAT]       = L"The .exe file is invalid (non-Microsoft Win32 .exe or error in .exe image).";
   errors[SE_ERR_ACCESSDENIED]    = L"The operating system denied access to the specified file.";
   errors[SE_ERR_ASSOCINCOMPLETE] = L"The file name association is incomplete or invalid.";
   errors[SE_ERR_DDEBUSY]         = L"The Dynamic Data Exchange (DDE) transaction could not be completed because other DDE transactions were being processed.";
   errors[SE_ERR_DDEFAIL]         = L"The DDE transaction failed.";
   errors[SE_ERR_DDETIMEOUT]      = L"The DDE transaction could not be completed because the request timed out.";
   errors[SE_ERR_DLLNOTFOUND]     = L"The specified DLL was not found.";
   errors[SE_ERR_FNF]             = L"The specified file was not found.";
   errors[SE_ERR_NOASSOC]         = L"There is no application associated with the given file name extension. This error will also be returned if you attempt to print a file that is not printable.";
   errors[SE_ERR_OOM]             = L"There was not enough memory to complete the operation.";
   errors[SE_ERR_PNF]             = L"The specified path was not found.";
   errors[SE_ERR_SHARE]           = L"A sharing violation occurred.";

   int ret = reinterpret_cast< int >( ::ShellExecute(0,L"open",L"\"C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Accessories\\Calculator.lnk\"",0,0,SW_SHOW) );
   const int minimumRetOK = 33;
   if ( ret < minimumRetOK ) {
      if ( errors.count( ret ) ) {
         std::wcout << L"Error " << ret << L" " << errors[ ret ];
      } else {
         std::wcout << L"Error " << ret << L" undocumented error";
      }
   }

    return 0;
}
4

3 回答 3

2

ShellExecute或者CreateProcess应该能够打开链接文件。如果他们找不到相关的文件和/或程序,您可以随时使用这些 API 并将繁重的工作委托给“cmd start”或“explorer”。例如ShellExecute(0, "open", "explorer", linkfile, 0, SW_SHOW);

于 2010-12-10T16:34:21.787 回答
1

我不确定您不确定什么,您观察到的行为已记录在案

ShellExecute“打开”操作将执行当您“打开”文件参数引用的文件时外壳程序所做的任何事情(您可以右键单击快捷方式并显式选择“打开”,但这也是 .lnk 的默认操作, 所以和双击一样)。

“打开”一个快捷方式文件,它将“打开”目标,如果目标是可执行文件,它将运行,如果是文档或数据文件,它将在关联的程序中打开,如果没有则提示输入程序联系。

于 2010-12-10T16:45:50.213 回答
1

ShellExecute应该管用。

但, ...

int main( int, wchar_t* )

...我所知道的没有编译器支持这个签名。写吧:

int main()

此外,对于诊断消息,只需使用FormatMessageWindows API 函数,或者,如果代码专门用于 Visual C++,则使用与该编译器捆绑的适当支持类。

干杯&hth.,

于 2010-12-10T16:54:03.920 回答