WPF使用桌面橋打包為UWP應用使用開機自啟的解決辦法
1.編輯桌面橋工程Package.appxmanifest檔案
引用名稱空間xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10
然後在節點下的節點中新增拓展
<desktop:Extension Category="windows.startupTask" Executable="xxxxxx.exe" EntryPoint="Windows.FullTrustApplication"> <desktop:StartupTask TaskId="xxxxxxAutoLaunchTask" Enabled="true" DisplayName="xxxxxx" /> </desktop:Extension>
Category為windows.startupTask
Executable為wpf應用的exe名稱
EntryPoint為Windows.FullTrustApplication
TaskId為應用的Id,需要有唯一性
DisplayName為顯示在工作管理員中啟動欄的名稱
2.如果需要在Wpf程式碼中控制應用是否自啟,則需要引用Win10SDK
右鍵選擇給工程Add References,開啟資料夾C:\Program Files (x86)\Windows Kits\10\UnionMetadata(Windows10 SDK的預設安裝路徑)
可以看到上圖存在16299,17134和17763三個版本,我這裡選擇了當前比較普及的17134版本(對應Windows 10 1803版本)。
僅僅新增這一項是不夠的,另一個必選項是
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
完成新增引用的操作後,就可以在WPF工程中使用StartupTask類了
1 var startupTask = await StartupTask.GetAsync("xxxxxxAutoLaunchTask"); 2 StartupTaskState State = startupTask.State; 3 4 switch(State) 5 { 6 case StartupTaskState.Disable; 7 //開啟開機自啟 8 State = await startupTask.RequestEnableAsync(); 9 break; 10 case StartupTaskState.DisableByUser; 11 //開機自啟被使用者手動關閉 12 break; 13 case StartupTaskState.DisableByPolicy; 14 //開機自啟被組策略關閉 15 break; 16 }
邏輯比較簡單,基本就是先獲取StartupTask物件,再根據使用者操作來Enable或Disable,之後返回更新後的StartupTaskState。
3.打包成UWP應用
完成上述操作後,若直接進行打包,則會報錯找不到xxx.exe
這時需要開啟打包專案檔案.wapproj
在ItemGroup節點下面,把wpf專案生成的所有檔案加進去,修改後如下
1 <ItemGroup> 2 <None Include="Package.StoreAssociation.xml" /> 3 <None Include="CpuMeterDesktopBridge_StoreKey.pfx" /> 4 <Content Include="Images\LargeTile.scale-100.png" /> 5 <Content Include="Images\LargeTile.scale-125.png" /> 6 <Content Include="Images\LargeTile.scale-150.png" /> 7 ... 8 <Content Include="Images\Wide310x150Logo.scale-400.png" /> 9 <Content Include="..\xxxxxx\bin\Release\xxxxx.exe"> 10 <CopyToOutputDirectory>Always</CopyToOutputDirectory> 11 </Content> 12 <Content Include="..\xxxxxx\bin\Release\System.Windows.Interactivity.dll"> 13 <CopyToOutputDirectory>Always</CopyToOutputDirectory> 14 </Content> 15 <Content Include="..\xxxxxx\bin\Release\CommonServiceLocator.dll"> 16 <CopyToOutputDirectory>Always</CopyToOutputDirectory> 17 </Content> 18 <Content Include="..\xxxxxx\bin\Release\GalaSoft.MvvmLight.dll"> 19 <CopyToOutputDirectory>Always</CopyToOutputDirectory> 20 </Content> 21 <Content Include="..\xxxxxx\bin\Release\GalaSoft.MvvmLight.Extras.dll"> 22 <CopyToOutputDirectory>Always</CopyToOutputDirectory> 23 </Content> 24 <Content Include="..\xxxxxx\bin\Release\GalaSoft.MvvmLight.Platform.dll"> 25 <CopyToOutputDirectory>Always</CopyToOutputDirectory> 26 </Content> 27 </ItemGroup>
如此操作後,WPF轉制的UWP應用即可正常開機自啟動
參考文件
1.https://www.imooc.com/article/268529
2.https://www.songshizhao.com/blog/blogPage/1400.html
3.https://blogs.windows.com/windowsdeveloper/2017/08/01/configure-app-start-log/