There are a number of ways of doing it.
You can use GetAncestor, GetParent or GetTopWindow.
Depending on the function you use, you may need to detect that the returned value isn't the desktop window.
The combination GetAncestor with GA_ROOT will likely do the trick for you. If not, one of the other two will. (the reason I'm not giving you a definite answer is because I'm not sure how the LCL manages windows but, one of those will do the "trick".) In a pure Windows API program, I use GetTopWindow without any problems.
ETA:
I forgot to mention GetTopLevelWindow (it's undocumented - too useful to be documented

) you can find an example which includes its definition and how to use it at
https://forum.lazarus.freepascal.org/index.php/topic,53469.msg395532.html#msg395532HTH.