unity 最小化windows游戏窗口

有两种方法,稍微有些区别,先贴代码

方法一

using System;
using System.Runtime.InteropServices;
using UnityEngine;

/// <summary>
/// 开始时最小化窗口
/// </summary>
public class SetWindowMin : MonoBehaviour
{
    
    
    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
    [DllImport("user32.dll")]
    static extern IntPtr GetActiveWindow();
    
    const int SW_SHOWMINIMIZED = 2; //{最小化, 激活}  
    const int SW_SHOWMAXIMIZED = 3;//最大化  
    const int SW_SHOWRESTORE = 1;//还原 

    private void Start()
    {
    
    
        ShowWindow(GetActiveWindow(), SW_SHOWMINIMIZED);
    }
}

这个方法获取的是本进程中的活动窗口,建议用这个

方法二

using System;
using System.Runtime.InteropServices;
using UnityEngine;

/// <summary>
/// 开始时最小化窗口
/// </summary>
public class SetWindowMin : MonoBehaviour
{
    
    
    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);

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

    const int SW_SHOWMINIMIZED = 2; //{最小化, 激活}  
    const int SW_SHOWMAXIMIZED = 3;//最大化  
    const int SW_SHOWRESTORE = 1;//还原 

    private void Start()
    {
    
    
        ShowWindow(GetForegroundWindow(), SW_SHOWMINIMIZED);
    }
}

这个方法获取的是整个windows系统中的焦点窗口,如果你在启动这个脚本时,点击了其他程序的活动窗口,那么将会最小化其他程序的窗口,不建议使用这个

猜你喜欢

转载自blog.csdn.net/weixin_44568736/article/details/122082393