using System.Runtime.InteropServices;
using UnityEngine;
public class WindowPosition : MonoBehaviour
{
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
private static extern bool SetWindowPos(IntPtr hwnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
[DllImport("user32.dll", EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(string className, string windowName);
void Start()
{
PositionWindow();
}
void PositionWindow()
{
// The window name can vary depending on the title you have set for your game window.
IntPtr windowPtr = FindWindow(null, "Your Unity Application Name");
if (windowPtr != IntPtr.Zero)
{
// Positions the window at the top-left corner of the screen with a size of 800x600.
// You can adjust these values according to your needs.
SetWindowPos(windowPtr, 0, 0, 0, 800, 600, 0x0040);
}
}
}
Unity自身并不直接提供设置窗口位置的API,但是你可以通过调用操作系统的API来达到目的。
首先,你需要在Unity项目中的C#脚本中声明对Windows API的调用。这通常涉及到使用DllImport
来引入user32.dll
库中的函数,比如SetWindowPos
,这个函数可以用来设置窗口的位置和大小。