0

I need to be able to run a Unity game inside a Visual Studio form for my school project.

I'm not that good yet with VS and this kind of stuff is still complicated for me and I don't even know if it is possible.

This is what I have:

And this is the result that I need:

Is this even possible? If so, how or point me in the right direction please.

EDIT: Found how to do it:

[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
private void button1_Click(object sender, EventArgs e)
{
var clientApplication = Process.Start("C:/Users/ricardo.coelho/Desktop/Unity_VS_Test.exe");
Thread.Sleep(500);
SetParent(clientApplication.MainWindowHandle, panel1.Handle);
}

1
  • As a side note, you should not use Thread.Sleep there if possible, as it is reliant of the speed of the PC components to load up Unity. First, see if clientApplicartion.WaitForInputIdle() is sufficient instead. It should be, but if it doesn't work you should make sure .MainWindowHandle is not null before calling SetParent, and if it is null you'll want to loop until it isn't; then you can use a Thread.Sleep inside the loop. Best to also make sure clientApplication.HasExited is false to be sure it didn't crash on launch, and handle it appropriately if it did. Commented Jan 18, 2016 at 16:15

1 Answer 1

0

Yes you can do that, via the command line parameters.

The parameter you are looking for is -parentHWND, as stated in the documentation. The documentation also contains an example that could help you out.

From there (in a C# application) it is a matter of

process = new Process();
process.StartInfo.FileName = "Child.exe";
process.StartInfo.Arguments = "-parentHWND " + panel1.Handle.ToInt32() + " " + Environment.CommandLine;
process.StartInfo.UseShellExecute = true;
process.StartInfo.CreateNoWindow = true;

process.Start();
process.WaitForInputIdle();
EnumChildWindows(panel1.Handle, WindowEnum, IntPtr.Zero);
Sign up to request clarification or add additional context in comments.

4 Comments

Interesting, is there any downside on this approach?
I haven't tried this myself, so I'm not entirely sure if all input is appropriately captured and provided to the Unity instance. That would be something to look out for. But if that works, it should be okay.
-parentHWND apparently is deprecated and removed as of Unity 4.6.
Not really afaik @user169771, unless you can show me a source. It was temporarily removed in 4.6, but added back as part of 5.0.1. I haven't checked lately if it's still around, but the documentation seems to suggest this is the case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.