Crash using SetWidgetToFocus in C++

Hi Guys,

I have a question about how to use SetWidgetToFocus in C++ properly.
I want whenever the widget is added to viewport, it will receive the focus, without clicking the mouse in the widget. I can do this using blueprint from GetPlayerController node, draw a SetInputModeUIOnly, and then give the Widget variable to the ‘Set Widget to Focus’ node. It works fine.
Then, I needed to set the input mode using C++, because I generated and added widget to Viewport using C++. I created a FInputModeUIOnly. Because SetWidgetToFocus method need a TSharedPtr, I pass Widget->TakeWidget() as argument. It worked fine in the Editor and when playing the game. However, I got crash when I exit from editor into my Visual Studio. Here is the screenshot.

There was no error If I didn’t call the SetWidgetToFocus method from FInputModeUIOnly.

Anyone knows how to use SetWidgetToFocus properly? I guess passing Widget->TakeWidget() as argument is not safe.

Thanks in advance for all your response and help.