2

I'm working with UWP and I use ContentDialog to show the content. I want to prevent user dismiss dialog by press ESC button. I tried this solution but when I set the Cancel = true. I cannot handle the click event in Primary Button:

How to prevent the ContentDialog from closing when home key is pressed in Windows phone 8.1..?

Do we have any way to prevent it? My purpose is locking the screen anyway.

Bui Quang Huy
  • 1,784
  • 2
  • 17
  • 50

4 Answers4

4

This is my solution:

 dialog.Closing += DialogClosingEvent;

 private void DialogClosingEvent(ContentDialog sender, ContentDialogClosingEventArgs args)
 {
      // This mean user does click on Primary or Secondary button
      if(args.Result == ContentDialogResult.None)
      {
           args.Cancel = true;
      }
 }
Bui Quang Huy
  • 1,784
  • 2
  • 17
  • 50
1
<Capabilities>
  <Capability Name="internetClient" />
  <rescap:Capability xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" Name="inputForegroundObservation"/>
</Capabilities>

Add the above permission in your application. in the Appxmanifest file. After adding the above code your manifest file may not open normally. Hence, you can open using the XML editor.

Dispatcher.AcceleratorKeyActivated += Dispatcher_AcceleratorKeyActivated;

private void Dispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args)
    {
        if(args.key == Windows.System.VirtualKey.Esc)
        {
           args.Handled = true;
        }
    }

The above code will disable the ESC button throughout the application.

0

A form dialog can be dismiss by pressing ESC if Form.CancelButton property is set to a button control (most probably the primary button you talk about).

Additionally, the dialog will close by pressing a button if Button.DialogResult is set.

You may want to check Primary Button DialogResult property.

Ricardo González
  • 1,385
  • 10
  • 19
0

You can try this workaround, though I think there's another better way to do it:

On MainPage.xaml.cs:

private async void ShowDialog()
{
   SampleDialog sampleDialog = new SampleDialog();
   await sampleDialog.ShowAsync();
}

On SampleDialog.xaml.cs:

    bool isEscape;

    public SampleDialog()
    {
        isEscape = true;
        this.InitializeComponent();
        this.Closing += SampleDialog_Closing;
    }

    private void SampleDialog_Closing(ContentDialog sender, ContentDialogClosingEventArgs args)
    {
        if (isEscape)
            args.Cancel = true;
    }

    private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
    {
        this.Title = "Primary button clicked";
    }

    private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
    {
        isEscape = false;
        this.Hide();
    }
Red David
  • 61
  • 4