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);