Pin screen blocking home button

Hello,

I am kind of new to roku development and BrightScript. I have managed to build a application, but there are elements that I wish to protect with a pin screen, the only problem is that all the screens that I call after the pin screen do not react to the “back” button on the remote.
I have bypassed the pin screen to see if there was something wrong with the other screens, and they are working ok as long as they do not come after pin screen.

This is the function that shows the pin screen

sub showPinScreen()

screen = CreateObject("roPinEntryDialog")
screen.setTitle("Confirm your identity")
screen.addButton(1,"Next")
screen.addButton(0,"Cancel")
screen.SetNumPinEntryFields(4)
port= CreateObject("roMessagePort")
screen.setMessagePort(port)
screen.show()
while true
     msg=wait(0, screen.GetMessagePort())
     
     if(msg.getIndex()=1)
        if(screen.pin()=regRead("pin", "authentication"))
        showSelectionScreen()
        screen.close()
         exit while
        else
            screen.close()
            showWrongPin()
            exit while
        endif
     end if
     if(msg.getIndex()=0)
         exit while
     end if
end while
 screen.close()
 Main()
end sub

Please tell me what I am doing wrong, or how I can make screens that are opened from the pin screen to react to the back button.

Usually, when checking for messages, you check type first, and you need to check for isscreenclosed() events and return from your sub if you encounter one:


if type(msg)="roPinEntryDialogEvent" then
if msg.isbuttonpressed() then
'check for msg.getindex() here and act accordingly

else if msg.isscreenclosed() then

return -1

Thank you Joel for your reply.
I will update my code with your recommendation, but I found the problem in the order the functions are called.
It seams that a screen will not return until it has ended, so the right way to get rid of the problem is to change this


if(msg.getIndex()=1)
        if(screen.pin()=regRead("pin", "authentication"))
        showSelectionScreen()
        screen.close()
         exit while
        else
            screen.close()
            showWrongPin()
            exit while
        endif
     end if

with this


if(msg.getIndex()=1)
        if(screen.pin()=regRead("pin", "authentication"))
        screen.close()
        showSelectionScreen()
         exit while
        else
            screen.close()
            showWrongPin()
            exit while
        endif
     end if

Notice that first I close the pin screen before I call the function that will show the selection screen.
This seams to fix the problem.