- Home /
How can I bring to front a window called by an script in unity?
Hello,
I'm trying to bring to front the unity game when it is not the active window.
I've tried implenting a dll and later importing de "user32.dll" but is not working.
The code is something like this:
using System; using System.Collections.Generic; using System.Threading; using System.Runtime.InteropServices; using System.Diagnostics; using UnityEngine; using System.Collections;
public class AccesoDLL : MonoBehaviour {
[DllImport("SimpleDLL")]
private static extern byte cSum(byte b1, byte b2);
[DllImport("SimpleDLL")]
private static extern int MinimizarVentana(int u);
[DllImport("SimpleDLL")]
private static extern int MaximizarVentana(int u);
[DllImport("SimpleDLL")]
private static extern int GetWindowHandler();
[DllImport("user32.dll")]
[return: MarshalAs (UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(int hWnd);
public int u;
void Awake() {
u = GetWindowHandler();
}
public void Minimizar () {
MinimizarVentana(u);
}
public void Maximizar () {
MaximizarVentana(u);
}
public void SetForegroundWindows(){
SetForegroundWindow(u);
}
}
The functions Maximizar and Minimizar are working on my own dll, but when I try yo use de API functions like SetForegroundWindow not work.
Does anybody know how to do this?
Thanks!
Answer by tteneder · May 05, 2015 at 08:14 AM
Here's my solution that works with Unity 5.0.1 and Windows 8.1:
using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
public class ForeGrounder : MonoBehaviour {
private const uint LOCK = 1;
private const uint UNLOCK = 2;
private IntPtr window;
void Start() {
LockSetForegroundWindow(LOCK);
window = GetActiveWindow();
StartCoroutine(Checker());
}
IEnumerator Checker() {
while (true) {
yield return new WaitForSeconds(1);
IntPtr newWindow = GetActiveWindow();
if (window != newWindow) {
Debug.Log("Set to foreground");
SwitchToThisWindow(window, true);
}
}
}
[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();
[DllImport("user32.dll")]
static extern bool LockSetForegroundWindow(uint uLockCode);
[DllImport("user32.dll")]
static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
}
I was using SetForegroundWindow and SetActiveWindow as this seems to be what everyone is recommending lately. This didn't work, though. The best I got was the icon flashing in the taskbar but the window never actually came to the foreground.
.
Using SwitchToThisWindow worked perfectly in 2019.4! Thank you... 5 years late, but thank you! :D
Your answer
Follow this Question
Related Questions
Is there a way to make a pc build that will not lose focus when selecting another app ? 1 Answer
stop unity pausing when it loses focus 4 Answers
Fullscreen does not pause music - Windows 7 1 Answer
Can't Move Around Run in Background is ON 0 Answers
Application reduced in task bar. force focus on app, always on top 0 Answers