Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to bring Unity3d to the foreground?

Tags:

c#

unity3d

I have sent my user out to the browser with Application.OpenURL. And now I want to programatically bring unity back to the foreground.

Is there any way to do it without a plugin?

Thanks.

like image 673
peterept Avatar asked Mar 17 '15 05:03

peterept


People also ask

How do I open Unity Project in Visual Studio?

Open Unity scripts in Visual Studio Once Visual Studio is set as the external editor for Unity, double-clicking a script from the Unity editor will automatically launch or switch to Visual Studio and open the chosen script.

How do I link Unity to Visual Studio?

Install Visual Studio and Unity Select Install, or Modify if Visual Studio is already installed. Select the Workloads tab, then select the Game development with Unity workload. If Unity isn't already installed, select Unity Hub under Optional. Select Modify or Install to complete the installation.


1 Answers

Use GetActiveWindow to get the window's handle before you send the user away, then use SetForegroundWindow using that handle. Before you use SetForegroundWindow, you can try simulating an Alt keypress to bring up a menu to abide by certain limitations of SetForegroundWindow:

private IntPtr unityWindow;

[DllImport("user32.dll")] 
static extern IntPtr GetActiveWindow();

[DllImport("user32.dll")] 
static extern bool SetForegroundWindow(IntPtr hWnd); 

[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);

const int ALT = 0xA4;
const int EXTENDEDKEY = 0x1;
const int KEYUP = 0x2;

private void SendUser() 
{
    unityWindow = GetActiveWindow();

    Application.OpenURL("http://example.com");

    StartCoroutine(RefocusWindow(30f));
}


private IEnumerator RefocusWindow(float waitSeconds) {
    // wait for new window to appear
    yield return new WaitWhile(() => unityWindow == GetActiveWindow());

    yield return new WaitForSeconds(waitSeconds);

    // Simulate alt press
    keybd_event((byte)ALT, 0x45, EXTENDEDKEY | 0, 0);

    // Simulate alt release
    keybd_event((byte)ALT, 0x45, EXTENDEDKEY | KEYUP, 0);

    SetForegroundWindow(unityWindow);
}
like image 180
Ruzihm Avatar answered Oct 04 '22 23:10

Ruzihm