![](/img/trans.png)
[英]How can I launch a C++ native application from a Windows Service main function (the application interacts with the console)?
[英]How can I launch programmatically (C++) an application from a Windows shortcut (.lnk file)?
如何從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;
}
ShellExecute
或CreateProcess
應該能夠打開鏈接文件。 如果他們找不到關聯的文件和/或程序,則可以始終使用這些API,並將辛苦的工作委派給“ cmd start”或“ explorer”。 例如ShellExecute(0, "open", "explorer", linkfile, 0, SW_SHOW);
我不確定您不確定什么,您觀察到的行為是否已記錄在案 。
ShellExecute的“打開”操作將執行外殼程序在“打開”由文件參數引用的文件時所做的任何操作(您可以右鍵單擊快捷方式並顯式選擇“打開”,但這也是.lnk的默認操作,因此與雙擊相同)。
“打開”快捷方式文件將“打開”目標,如果目標是可執行文件,它將運行,如果它是文檔或數據文件,它將在關聯的程序中打開,如果沒有則提示輸入程序相關。
ShellExecute
應該工作。
但是...
int main( int, wchar_t* )
...據我所知沒有編譯器支持此簽名。 寫吧:
int main()
另外,對於診斷消息,只需使用FormatMessage
Windows API函數,或者,如果代碼專用於Visual C ++,則使用與該編譯器捆綁在一起的相應支持類。
干杯,……
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.