Unable to get top level window handles when run a .bat script from Jenkins

I have a program that looks up an existing process on Jenkins node, finds all its threads and find top level windows handles.
I call this program from a .bat file.
The program and .bat file are residing on Jenkins node.
When I log into this Jenkins Node, run the .bat file manually, it able to identify top level windows handles for the specified process. So it works just fine. However when I call this .bat file from Jenkins, looks like it able to find the process, but not the its associated handles. Could this possibly an issue with Jenkins’ settings? Any idea?
thank you

This is the piece of code where it is failing when running from Jenkins, but runs fine when manually trigger the script. I printed out handle counts at the end, when running it manually, I get a count of 7, but from Jenkins, I get ‘0’ as the value.
internal static IEnumerable EnumerateProcessWindowHandles(int processId)
var handles = new List();

        foreach (ProcessThread thread in Process.GetProcessById(processId).Threads)
            Console.WriteLine("Thread id: " + thread.Id);

                (hWnd, lParam) => { handles.Add(hWnd); return true; }, IntPtr.Zero);

        Console.WriteLine("handle counts: " + handles.Count);
        return handles;

Is this running on the controller or an agent? If the controller, I assume you are running Jenkins as a service? If agent, are you running the agent as a service (inbound agent)? When an application is running as a service, it generally cannot interact with the desktop. There are some workarounds that you can try if you google.

Thanks for your quick response on this Alex.
I have tried both running it on the agent, and also on the master (controller), both are behaving the same. And yes, the agent is running as a service. I’ve also tried marking the Jenkin service with option “Allow service to interact with desktop”, but no luck.

This page may help: .net - Jenkins on Windows and GUI Tests without RDC - Stack Overflow looks like the story on Windows for this is not great right now.

Thanks for sending more info. From your suggestion above, I have disabled the agent “service” and just run the agent via command line. This workaround seems to work for me and will go with that for now.