Problem with cmd.exe when we use process.start c#

Nicolas DEVILLE 21 Reputation points
2023-10-16T19:50:04.5233333+00:00

Good morning,

I am currently developing an application allowing the integration of several processes (application, like superputty does for putty) in a Windows Forms. This works for quite a few applications (like remote desktop), however, when I start cmd.exe, I have the correct pid, but I cannot retrieve the corresponding handle. CMD may start several handles in different processes.

Thank you very much in advance.

Here is part of the code:

m_Process.Start();
// attendre que le process soit disponible
m_Process.WaitForInputIdle();
//m_Process.Refresh(); // ??
// recup du handle de l'appli
m_Handle = m_Process.MainWindowHandle;
if (m_Handle == IntPtr.Zero)
{
    DateTime startTime = DateTime.Now;
    while ((DateTime.Now - startTime).TotalSeconds < 10 && m_Handle == IntPtr.Zero)
    {
        System.Threading.Thread.Sleep(50);

        // Refresh Process object's view of real process
        m_Process.Refresh();
        m_Handle = m_Process.MainWindowHandle;
    }
}
// put exe in the user control
if (m_Handle == IntPtr.Zero)
    MessageBox.Show("Handle nul");
Developer technologies C#
{count} votes

Accepted answer
  1. KOZ6.0 6,655 Reputation points
    2023-10-17T19:47:12.23+00:00

    Wait a moment for MainWindowHandle to become valid.
    Perform timeout processing if necessary.:)

    private void button1_Click(object sender, EventArgs e) {
        Process p = new Process {
            StartInfo = new ProcessStartInfo {
                FileName = "cmd.exe",
                WindowStyle = ProcessWindowStyle.Minimized
            }
        };
        p.Start();
        while (p.MainWindowHandle == IntPtr.Zero) {
            Thread.Sleep(100);
        }
        if (SetParent(p.MainWindowHandle, Handle) == IntPtr.Zero) {
            throw new Win32Exception();
        }
    }
    
    [DllImport("User32", SetLastError = true)]
    private static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);
    

    enter image description here

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.