This is a years-long problem with the Magic Keyboard if all the comments in Apple Community Support is any measure. Many responses have been deleted by Apple. Essentially this keyboard has a Lock button in the upper right corner just above the “delete” button. Most people will occasionally hit the Lock button which closes down the desktop until the password it typed in which of course interrupts workflow.
Any new info about this or better yet, a cure. Going to Keyboard in System Settings offers no fix.