Stop a process from showing a window from C#

匆匆过客 提交于 2019-12-07 15:04:15

问题


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?


回答1:


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.




回答2:


The CreateNoWindow option only applies to console mode applications, you cannot prevent a GUI app from creating its main window. Your best bet is the WindowStyle property, set it to Hidden or Minimized. A well behaved GUI app uses it in its call to ShowWindow(). But it certainly not unusual for it to override or ignore this value. Odds are not good in your case, Minimized is all you got left to try.




回答3:


Try option 1 with UseShellExecute =true, and WindowStyle = ProcessWindowStyle.Hidden or do not set UseShellExecute (it defaults to true)




回答4:


Why don't you just set the Startup Object property of your WinForm project? You can start the process without showing the Form or the actual window.

    static class Program {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        // Application.Run(new Form1());
        // TODO: Start you process here?
    }

Hope this help, thanks.




回答5:


Could you override the form Paint and blit in the contents of the desktop for the entire form region in order to get over the 16th second?

I'm a relative newbie to low level win forms stuff, but i was just having fun with OnPaint recently so I thought of this.



来源:https://stackoverflow.com/questions/5724759/stop-a-process-from-showing-a-window-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!