天天看點

Unity | 實作隐藏視窗到托盤,并且工作列不顯示icon

 效果如下圖所示:

Unity | 實作隐藏視窗到托盤,并且工作列不顯示icon

用到的插件:(放在Plugins檔案夾下,點選下載下傳各個版本)

  1. System.Drawing.dll
  2. System.Windows.Forms.dll
  3. System.Deployment.dll(運用基于.Net4.x的dll打包時,需要用到該dll,否則會報錯)

代碼如下:

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

public class LayoutManager : MonoBehaviour
{
    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();

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

    private const int SW_HIDE = 0;  //hied task bar

    private const int SW_RESTORE = 9;//show task bar
    
    private static System.Windows.Forms.NotifyIcon _notifyIcon = new System.Windows.Forms.NotifyIcon();

    private static int _width = 100, _height = 100;

    public Button btn;

    private IntPtr window;
   
    private void Start()
    {
        btn.onClick.AddListener(delegate
        {
            HideTaskBar();
        });
    }
    
    public void HideTaskBar()//最小化到托盤
    {
        try
        {
            window = GetForegroundWindow();

            ShowWindow(window, SW_HIDE);

            _notifyIcon.BalloonTipText = "AIScanner1.1.0";//托盤氣泡顯示内容

            _notifyIcon.Text = "AIScanner";//滑鼠懸浮時顯示的内容

            _notifyIcon.Visible = true;//托盤按鈕是否可見

            _notifyIcon.Icon = CustomTrayIcon(Application.streamingAssetsPath + "/icon.png", _width, _height);//托盤圖示

            _notifyIcon.ShowBalloonTip(2000);//托盤氣泡顯示時間

            _notifyIcon.MouseClick += notifyIcon_MouseClick;//輕按兩下托盤圖示響應事件
        }
        catch(Exception e)
        {
            Debug.Log(e.ToString());
        }
    }

    private static System.Drawing.Icon CustomTrayIcon(string iconPath, int width, int height)
    {
        System.Drawing.Bitmap bt = new System.Drawing.Bitmap(iconPath);

        System.Drawing.Bitmap fitSizeBt = new System.Drawing.Bitmap(bt, width, height);

        return System.Drawing.Icon.FromHandle(fitSizeBt.GetHicon());
    }

    private void notifyIcon_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)//點選托盤圖示
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            _notifyIcon.MouseDoubleClick -= notifyIcon_MouseClick;

            _notifyIcon.Visible = false;

            ShowWindow(window, SW_RESTORE);
        }
    }

    private void OnDestroy()
    {
        _notifyIcon.MouseDoubleClick -= notifyIcon_MouseClick;
    }
}


           

打包時,注意Unity ->PlayerSetting->Scripting Runtime Version及APi Compatibility Level倆個選項。