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/