Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

c# - UWP on desktop closed by top X button - no event

An UWP app which runs on desktop can be closed from the top X button but it doesn't have any event for it. It is known that on phones and tablets an app should rely on Suspending event, no matter how it's triggered and then the app should rely on ApplicationExecutionState.

However, here is a (maybe) common scenario: on phones the Suspending event suffice and in case a Voip call is going on it will be operated by OS after the app is suspended. On desktop the close button is expected, by user, to completely close the app. So if a call is on going it should be hanged up and certain resources should be released.

How can I know when the user clicked the "close" button if (and only if) the UWP app is running on desktop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A restricted capability confirmAppClose was added in Windows 10 version 1703 (build 10.0.15063) in order to provide apps the ability to intercept window closing.

Manifest namespace:

xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"

Manifest:

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

It needs extra approval when submitting to the store. But then will fire the CloseRequested event on a SystemNavigationManagerPreview instance.

Code:

    public MainPage()
    {
        this.InitializeComponent();
        SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += this.OnCloseRequest;
    }

    private void OnCloseRequest(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
    {
        if (!saved) { e.Handled = true; SomePromptFunction(); }
    }

You can get a deferral to do a bit of work here (save or prompt), or you can set Handled to true in order to stop the window from closing (user cancelled prompt).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...