Search code examples
c#winapiprocesspinvokewin32-process

Stop a process from showing a window from C#


I'm trying to automate an application that creates a GUI window on startup that has no user interaction, but I can't figure out how to hide the actual window.

I've tried using ProcessStartInfo thus:

Process.Start(new ProcessStartInfo {
    UseShellExecute = false,
    CreateNoWindow = true,
    WindowStyle = ProcessWindowStyle.Hidden,

    // other properties here
});

But the window still shows up.

I've also tried spin-waiting for the window to exist, and then hiding it:

while (process.MainWindowHandle == IntPtr.Zero) {}
ShowWindowAsync(process.MainWindowHandle, SW_HIDE);

This, unfortunately, makes the window flash for about 1/16th of a second or so, and I'd like to avoid it if at all possible.

My current thoughts are along the line of creating a hook, but am unsure of what hooks to grab, nor if it will even work.

Any tips?


Solution

  • The desired process window style (actually mapped to one of the SW_ constants) is passed to the other application's WinMain function, but that doesn't mean a rude application won't just ignore whatever value you send.

    You can pull it off by creating another virtual desktop using User32.CreateDesktop, then use Kernel32.CreateProcess, making sure to pass the correct desktop name as part of the STARTINFO structure.