本主題說明如何建立應用程式的快捷方式、為其指派 AppUserModelID,並在 [開始] 畫面中安裝。 強烈建議您在 Windows Installer 中執行這項作,而不是在應用程式的程式代碼中執行此動作。 若未在 \[開始\] 畫面或 \[所有程式\]中安裝有效的捷徑,您無法從桌面應用程式引發通知提示。
注意
本主題中使用的方法範例,來自 桌面版快顯通知範例。
您需要知道的事項
技術
- COM
先決條件
- 圖書館
- C++:Runtime.object.lib
- C#:Windows.Winmd
- C#:適用於 Microsoft .NET Framework 的 Windows API 程式代碼套件
- 支援至少 Windows 8 的 Microsoft Visual Studio 版本
指示
步驟 1:準備要建立的快捷方式
此範例會先透過 getEnvironmentVariable 函式,判斷使用者應用程式資料資料夾的路徑。 然後,它會撰寫快捷方式的完整路徑、判斷該名稱的快捷方式不存在於該位置,並將該資訊傳遞至另一個建立並安裝快捷方式的方法。
請注意,快捷方式可以按每個用戶或按每個應用程式進行部署。
HRESULT DesktopToastsApp::TryCreateShortcut()
{
wchar_t shortcutPath[MAX_PATH];
DWORD charWritten = GetEnvironmentVariable(L"APPDATA", shortcutPath, MAX_PATH);
HRESULT hr = charWritten > 0 ? S_OK : E_INVALIDARG;
if (SUCCEEDED(hr))
{
errno_t concatError = wcscat_s(shortcutPath, ARRAYSIZE(shortcutPath), L"\\Microsoft\\Windows\\Start Menu\\Programs\\Desktop Toasts App.lnk");
hr = concatError == 0 ? S_OK : E_INVALIDARG;
if (SUCCEEDED(hr))
{
DWORD attributes = GetFileAttributes(shortcutPath);
bool fileExists = attributes < 0xFFFFFFF;
if (!fileExists)
{
hr = InstallShortcut(shortcutPath); // See step 2.
}
else
{
hr = S_FALSE;
}
}
}
return hr;
}
步驟 2:建立快捷方式,並在 \[開始\] 畫面中安裝
此範例也會擷取快捷方式的屬性存放區,並從先前定義的變數設定必要的 System.AppUserModel.ID 屬性,AppID。
HRESULT DesktopToastsApp::InstallShortcut(_In_z_ wchar_t *shortcutPath)
{
wchar_t exePath[MAX_PATH];
DWORD charWritten = GetModuleFileNameEx(GetCurrentProcess(), nullptr, exePath, ARRAYSIZE(exePath));
HRESULT hr = charWritten > 0 ? S_OK : E_FAIL;
if (SUCCEEDED(hr))
{
ComPtr<IShellLink> shellLink;
hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink));
if (SUCCEEDED(hr))
{
hr = shellLink->SetPath(exePath);
if (SUCCEEDED(hr))
{
hr = shellLink->SetArguments(L"");
if (SUCCEEDED(hr))
{
ComPtr<IPropertyStore> propertyStore;
hr = shellLink.As(&propertyStore);
if (SUCCEEDED(hr))
{
PROPVARIANT appIdPropVar;
hr = InitPropVariantFromString(AppId, &appIdPropVar);
if (SUCCEEDED(hr))
{
hr = propertyStore->SetValue(PKEY_AppUserModel_ID, appIdPropVar);
if (SUCCEEDED(hr))
{
hr = propertyStore->Commit();
if (SUCCEEDED(hr))
{
ComPtr<IPersistFile> persistFile;
hr = shellLink.As(&persistFile);
if (SUCCEEDED(hr))
{
hr = persistFile->Save(shortcutPath, TRUE);
}
}
}
PropVariantClear(&appIdPropVar);
}
}
}
}
}
}
return hr;
}
備註
作為本主題所示方法的替代方案,您可以使用 Windows Installer XML (WiX) 之類的架構來產生快捷方式,並將其部署為 Windows Installer 的一部分。 在此情況下,此程式代碼應該包含在 MSI 中,而不是包含在應用程式的程式碼中。 如需詳細資訊,請參閱 從傳統型應用程式傳送快顯通知 範例隨附的範例 WiX 組態檔。
相關主題