UWP 调用Win32 关机

话说最近程序须要个晚上自动关机的功能windows

原则上 uwp 应该是没有关机权限的api

上网搜索之app

有人说只要这样就能够了ide

var psi = new ProcessStartInfo("shutdown", "/s /t 0");
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process.Start(psi);

可是使用这个必需要用 Brokered UWP Component Project Templates:spa

https://marketplace.visualstudio.com/items?itemName=LanceContreras.BrokeredUWPComponentProjectTemplates3d

这个 Templates 是 vs2015 的调试

 

不过个人是 vs2017rest

并且代码已经不少了,从头开始确定不行code

可是在 VS2017 下,如今能够直接调用 Win32 程序xml

在这里就能够调用 Win32 来进行关机

 

首先随便写个关机的程序

好比咱们直接开个控制台程序,写上:

        static void Main(string[] args)
        {
            Process.Start("shutdown.exe", "-s -f -t 100");
        }

设置程序开启后100秒关机 (话说设置100秒主要为了调试方便,只要运行 shutdown –a 就能够取消关机任务)

编译后生成 ConsoleShutdown1.exe

咱们把文件拷贝到uwp的目录下面

我单独建了个文件夹,把exe文件包含到项目中:

image

 

而后咱们添加引用 “ Windows Desktop Extensions For The UWP ”,添加那个版本看本身的项目须要了,我项目的目标版本直接就是1709,因此直接引用最新版的扩展。

(注意要在 UWP 中调用 Win32 程序,Windows Desktop Extensions For The UWP 的最低版本为 14393,也就是说对方的win10最低也要为1607)

image

 

而后咱们须要编辑 Package.appxmanifest 文件

直接查看代码:

image

 

在 Package 节点上,咱们要加上 rescap 和 desktop 的引用,注意下面的 IgnorableNamespaces 要加上rescap ,否则你生成应用程序包的时候能够会提示配置文件错误。

<Package
  xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
  xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
  xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
  xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
  xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10"
  IgnorableNamespaces="uap mp rescap">

 

而后修改 Capabilities 节点,加上 <rescap:Capability Name="runFullTrust"/>

  <Capabilities>
    <Capability Name="internetClient" />
    <rescap:Capability Name="runFullTrust"/>
  </Capabilities>

 

最后在 Application 节点中加入 Extensions 节点,里面包含咱们的 Win32 程序在项目中的路径

  <Applications>
    <Application Id="App"
      Executable="$targetnametoken$.exe"
      EntryPoint="AppShutdown1.App">
      <uap:VisualElements
        DisplayName="AppShutdown1"
        Square150x150Logo="Assets\Square150x150Logo.png"
        Square44x44Logo="Assets\Square44x44Logo.png"
        Description="AppShutdown1"
        BackgroundColor="transparent">
        <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png"/>
        <uap:SplashScreen Image="Assets\SplashScreen.png" />
      </uap:VisualElements>
      <Extensions>
        <desktop:Extension Category="windows.fullTrustProcess" Executable="Exe\ConsoleShutdown1.exe" />
      </Extensions>
    </Application>
  </Applications>

 

基本就大功告成了

下面就是在须要调用 Win32 程序的地方 写上:

await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();

 

就能够在UWP 中调用 Win32 程序了

这里我就能够调用 shutdown 来关机

 

并且即便在  “设置分配的访问权限” 下,也是能够正常调用 Win32程序 的

image

 

 

此外在调用 Win32 程序的时候还能够加参数(若是 Win32 程序支持的话)

更多见: https://docs.microsoft.com/en-us/uwp/api/windows.applicationmodel.fulltrustprocesslauncher

相关文章
相关标签/搜索