Can you manipulate other Windows?

Sorry if this is a repost, It did not show it come up and on my profile it said I had 0 questions so hopefully it is not. I was wondering if there were any commands in unity to manipulate other windows. I know you can create and manipulate your own but what about others, such as locking a game window to stop it deactivating when clicking on a second monitor?

1 Answer

1

I still don’t quite understand the use case - you want to create a Unity application that prevents another application (e.g. Tf2) from losing focus when a second monitor is clicked? That’s very abstract, but certainly possible - you can use InterOp services from C# to call into the Windows API. I think SetWindowPos is what you’re after:

–edit–

Here’s an example for you. I don’t have Team Fortress installed, so I’m using Windows Calculator instead. Copy this into a new C# script and attach it to a gameobject. Then, fire up calculator, run the scene and click in your Unity player.

You can play with different flags as to whether it loses/gains focus, comes to the front etc. I’ll just make it move around the screen:

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System;
using System.Diagnostics;

public class ControlOtherWindow : MonoBehaviour {

	// Used to get the appropriate window handle
	[DllImport("User32.dll")]
	public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int W, int H, uint uFlags);

	// Used to resize and position a window
	[DllImport("User32.dll")]
	public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

	// Flag to not give the other window focus
	private const int SWP_NOACTIVATE = 0x0010;

	// Simple two state toggle
	bool toggle = true;
	
	// Update is called once per frame
	void Update () {
	
		if(Input.GetMouseButtonDown(0)){ 

			// Get a handle for the Calculator window
			IntPtr handle = FindWindow(null, "Calculator");
			if(handle != IntPtr.Zero){
				if(toggle)
					SetWindowPos(handle,IntPtr.Zero,100,100,400,300,SWP_NOACTIVATE);
				else
					SetWindowPos(handle,IntPtr.Zero,400,400,200,300,SWP_NOACTIVATE);
				toggle = !toggle;
			}
		}
	}

	void OnGUI () {
		GUI.Label (new Rect(10,10,400,300), "Load up Windows calculator.exe and then click in this window");
	}
	
}

33996-anim.gif

No you can't hack other players with Unity

Example added.

Thank you for your answer tanoshimi, it is greatly appreciated. I will certainly look into the link you sent me to find the right commands for the job