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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With