您当前的位置: 首页 >  游戏
  • 3浏览

    0关注

    193博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

unity游戏窗口最小化、最大化以及隐藏标题栏

我寄人间雪满头丶 发布时间:2021-08-26 11:31:18 ,浏览量:3

效果 在这里插入图片描述

代码

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

public class WindowsStyle : MonoBehaviour
{
    public Button hideBarBtn;
    public Button showBarBtn;
    public Button hideCloseBtn;
    public Button showCloseBtn;
    public Button showMaxSizeBtn;


    private void Awake()
    {
        // 获得窗口句柄
        var hwd = GetForegroundWindow();
        // 隐藏标题栏
        hideBarBtn.onClick.AddListener(() =>
        {
            var wl = GetWindowLong(hwd, GWL_STYLE);
            wl &= ~WS_CAPTION;
            SetWindowLong(hwd, GWL_STYLE, wl);
        });
        // 显示标题栏
        showBarBtn.onClick.AddListener(() =>
        {
            var wl = GetWindowLong(hwd, GWL_STYLE);
            wl |= WS_CAPTION;
            SetWindowLong(hwd, GWL_STYLE, wl);
        });
        // 隐藏关闭按钮
        hideCloseBtn.onClick.AddListener(() =>
        {
            var wl = GetWindowLong(hwd, GWL_STYLE);
            wl &= ~WS_SYSMENU;
            SetWindowLong(hwd, GWL_STYLE, wl);
        });
        
        // 显示关闭按钮
        showCloseBtn.onClick.AddListener(() =>
        {
            var wl = GetWindowLong(hwd, GWL_STYLE);
            wl |= WS_SYSMENU;
            SetWindowLong(hwd, GWL_STYLE, wl);
        });
        
        // 窗口最大化按钮按钮
        showMaxSizeBtn.onClick.AddListener(() =>
        {
            /// 
			/// 最大化
			/// 
			// 设置窗口最大化
			ShowWindow(hwd, SW_SHOWMAXIMIZED);
        });
		
		/// 
    	/// 点击窗口的x按钮,会执行这个函数
   	 	/// 
 	   private void OnApplicationQuit()
	   {
        	Application.wantsToQuit += () =>
        	{
            	// 获得窗口句柄
            	var hwd = GetForegroundWindow();
            	// 设置窗口最小化
            	ShowWindow(hwd, SW_SHOWMINIMIZED);
            	// 阻止程序被关闭
            	return false;
        	};
		}
	}

	//引用windows接口
    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hwd, int cmdShow);

    [DllImport("user32.dll")]
    public static extern long GetWindowLong(IntPtr hwd, int nIndex);

    [DllImport("user32.dll")]
    public static extern void SetWindowLong(IntPtr hwd, int nIndex, long dwNewLong);

    /// 
    /// 最小化
    /// 
    const int SW_SHOWMINIMIZED = 2;

    /// 
    /// 最大化
    /// 
    const int SW_SHOWMAXIMIZED = 3;

    /// 
    /// 还原
    /// 
    const int SW_SHOWRESTORE = 1;

    /// 
    /// 窗口风格
    /// 
    const int GWL_STYLE = -16;
    /// 
    /// 标题栏
    /// 
    const int WS_CAPTION = 0x00c00000;
    /// 
    /// 标题栏按钮
    /// 
    const int WS_SYSMENU = 0x00080000;
}

如果是需要尽早执行的话可以推荐将代码放到[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]特性下调用。 RuntimeInitializeOnLoadMethod介绍

原文地址

关注
打赏
1648518768
查看更多评论
立即登录/注册

微信扫码登录

0.0508s