Starting a process without stealing focus (C#)

后端 未结 2 1663
谎友^
谎友^ 2020-12-05 14:52

I need to be able to start processes (both console and windowed) without it stealing focus. The only way within the .NET framework that I found to do this is Microsoft.Visu

2条回答
  •  旧巷少年郎
    2020-12-05 15:58

    Have a look here:

    System.Diagnostics.ProcessStartInfo procInfo = new System.Diagnostics.ProcessStartInfo();
    procInfo.CreateNoWindow = true;
    procInfo.UseShellExecute = true;
    procInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo = procInfo;
    proc.EnableRaisingEvents = true;
    proc.Exited += new EventHandler(proc_Exited);
    proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
    proc.Start(...)
    // Do something with proc.Handle...
    void  proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
       /* Do something here... */
    }
    
    void  proc_Exited(object sender, EventArgs e)
    {
    /* Do something here... */
    }
    

    Edit: I have modified the code to show the means of raising events and handling them, also, I have shown the usage of the Handle property which is the handle of the process that is running.

提交回复
热议问题