Forum Discussion

tsmith92765's avatar
tsmith92765
Copper Contributor
Jan 18, 2023

MessageBox not able to click "X" on the msgbox and cancel the script from continuing.

Hello PS Community!  I have a message box that works perfectly fine, but I want to adjust my code to be able to cancel the script upon clicking the big red "X" on the message box that pops up.

 

I tried looking into discussion posts but all the ones I see mention the "Yes" "No" "Cancel" buttons and adding actions to them. Is there any way we can make the "X" as a button I can influence like the above. To Exit the Script when clicked.

 

Any Suggestions would be greatly appreciated!

 

This is my code:

 

    Add-Type -AssemblyName PresentationFramework
    $ButtonType = [System.Windows.MessageBoxButton]::Ok
    $MesssageIcon = [System.Windows.MessageBoxImage]::Warning
    $MessageBody = "Please save anything open in your current Web Browser, this includes Google Chrome, Microsoft Edge, and Mozilla FireFox and close each one respectively.
    We will be deleting your cache and cookies.

    -IT"
    $MessageTitle = "Read Me"
    $Result = [System.Windows.MessageBox]::Show($MessageBody, $MessageTitle,$ButtonType,$MesssageIcon)
    • tsmith92765's avatar
      tsmith92765
      Copper Contributor

      Hey Vinod_5,

       

      I tried your suggestion and it worked! I added a Cancel button, then a Switch Case for when Cancel is hit it'll exit the script running, and from the link I noticed the "X" will call to MessageBoxShow.Cancel value. Making the "X" the same as hitting Cancel.

       

      Thank you for the advice!

       

      $MsgBox = {

          Add-Type -AssemblyName PresentationFramework
          $ButtonType = [System.Windows.MessageBoxButton]::OkCancel
          $MesssageIcon = [System.Windows.MessageBoxImage]::Warning
          $MessageBody = "Please save anything open in your current Web Browser, this includes Google Chrome, Microsoft Edge, and Mozilla FireFox and close each one respectively.
          We will be deleting your cache and cookies.

          -IT"
          $MessageTitle = "Read Me"
          $Result = [System.Windows.MessageBox]::Show($MessageBody, $MessageTitle,$ButtonType,$MesssageIcon)

          $Result

          Switch ($Result){
              'Ok' {
                  Continue
              }
              'Cancel' {
                  Exit
              }
          }

      }

      # Invoke MsgBox as CurrentUser. #
      invoke-command -scriptblock $MsgBox

Resources