What the heck I'm doing wrong? I'm trying to avoid a lost device when alt-tabbing a fullscreen application.

I have BeginScene function which is called begining of main loop. In BeginScene function I check for lost device with TestCooperativeLevel function. If device is lost BeginScene returns result of TestCooperativelevel and exists.

In main loop, when calling the BeginScene I check if it fails and then it doen't enter in the game loop. And when the BeginScene is called again. I check the CooperativeLevel (of course) and if it's "device no reset" state I reset the device, return "failure" to main loop and exit from function.

And next time, when main loop calls BeginScene all should be fine and rendering should occur, but that never happens. What I'm doing wrong?

Code:
function BeginScene: HRESULT;
var
  hr: HRESULT;
begin

  hr := Device.TestCooperativeLevel;

  if hr = D3DERR_DEVICELOST then begin
    Result := hr;
    Exit;
  end;

  if hr = D3DERR_DEVICENOTRESET then begin
    Device.Reset(FD3DPP);
    Result := hr;
    Exit;
  end;

  Device.Clear(0, nil, D3DCLEAR_TARGET, $000000, 1, 0);

  Result := Device.BeginScene;
end;


While uMsg <> WM_QUIT do begin
    if GameWindow.Active then
      MsgWaiting &#58;= PeekMessage&#40;uMsg, 0, 0, 0, PM_REMOVE&#41;
    else
      MsgWaiting &#58;= GetMessage&#40;uMsg, 0, 0, 0&#41;;

    if MsgWaiting then begin
      TranslateMessage&#40;uMsg&#41;;
      DispatchMessage&#40;uMsg&#41;;
      Continue;
    end;

    GameTimer.Update;

    // Check if we could begun 3D drawing.
    if GameDX.BeginScene = D3D_OK then begin
      
     // Game code here. If application is ALT-TABed then this is section is never ran.

      GameDX.EndScene;
    end; 
end;