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

相關文章
相關標籤/搜索