当前位置: 首页 > news >正文

在unity中实现隐藏窗口,显示系统托盘图标,右键菜单退出功能

需要导入Targets .NET 3.5的System.Windows.Forms

using UnityEngine;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;

public class SystemTrayIcon : MonoBehaviour
{
    private NotifyIcon notifyIcon;
    private ContextMenuStrip contextMenu;

    // 引入 Windows API 函数
    [DllImport("user32.dll")]
    private static extern bool ShowWindow(System.IntPtr hWnd, int nCmdShow);
    [DllImport("user32.dll")]
    private static extern System.IntPtr GetActiveWindow();
    [DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(System.IntPtr hWnd);

    private const int SW_HIDE = 0;

    void Awake()
    {
        // 隐藏窗口
        System.IntPtr hWnd = GetActiveWindow();
        ShowWindow(hWnd, SW_HIDE);

        // 创建上下文菜单
        contextMenu = new ContextMenuStrip();
        ToolStripMenuItem exitMenuItem = new ToolStripMenuItem("退出");
        exitMenuItem.Click += ExitMenuItem_Click;
        contextMenu.Items.Add(exitMenuItem);

        // 创建系统托盘图标
        notifyIcon = new NotifyIcon();
        notifyIcon.Icon = new Icon(UnityEngine.Application.streamingAssetsPath + "/icon.ico"); // 替换为你的图标路径
        notifyIcon.Text = "Unity 系统托盘图标";
        notifyIcon.ContextMenuStrip = contextMenu;
        notifyIcon.Visible = true;
        notifyIcon.MouseDoubleClick += NotifyIcon_MouseDoubleClick;
    }

    private void NotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            // 双击图标时将 Unity 窗口置于前台
            System.IntPtr hWnd = GetActiveWindow();
            SetForegroundWindow(hWnd);
        }
    }

    private void ExitMenuItem_Click(object sender, System.EventArgs e)
    {
        // 退出应用程序
        notifyIcon.Visible = false;
        notifyIcon.Dispose();
        UnityEngine.Application.Quit();
    }

    void OnApplicationQuit()
    {
        // 在应用程序退出时释放资源
        if (notifyIcon != null)
        {
            notifyIcon.Visible = false;
            notifyIcon.Dispose();
        }
    }
}

相关文章:

  • springMvc
  • Ai模型-PyTorch和Tensorflow的区别
  • 【2024 CSDN博客之星】大学四年,我如何在CSDN实现学业与事业的“双逆袭”?
  • 09Elasticsearch02
  • SQL数据处理函数全解析
  • 使用Python脚本下载王者**游戏英雄皮肤原画图片(含源码)
  • JavaScript表单介绍
  • 发现一个挺好的项目,可以在springboot项目中快速接入DeepSeek API,有需要的可以尝试一下
  • 从0到1:STM32温控系统开发踩坑指南
  • http 响应码影响 video 标签播放视频
  • 关于JavaScript中的事件
  • 【Linux-命令】
  • Unity 开发资源汇总 | 插件 | 模型 | 源码(不断更新中,建议收藏)
  • 线上就医全流程医药机构接入文档接口代码-医保就医接口php-demo版本
  • 基于SSM+Vue的智能汽车租赁平台设计和实现(源码+文档+部署讲解)
  • 亚马逊云科技 re:Invent 2023:科技前沿风向标,探索未来云计算之窗
  • c# -01新属性-模式匹配、弃元、析构元组和其他类型
  • zookeeper有序临时结点实现公平锁的实践例子
  • Python 中从零开始的随机梯度下降
  • Java获取html标签内容中的图片链接
  • 发表“男性患子宫肌瘤”论文的杂志一年发文三千余篇,中介称可提供代写
  • “穿越看洪武”,明太祖及其皇后像台北故宫博物院南园展出
  • 联合国秘书长古特雷斯呼吁印巴保持最大克制
  • 山大齐鲁医院通报“子宫肌瘤论文现男性患者”:存在学术不端
  • 解放军仪仗司礼大队仪仗分队参加纪念苏联伟大卫国战争胜利80周年阅兵活动
  • 特朗普关税风暴中的“稳”与“变”:新加坡国会选举观察