做展厅项目或者其它定制化桌面程序,经常需要设置开机自启动,且把无关的窗口最小化。
本人试过在开机自启的时候写txt脚本让某程序最小化,结果不太如意。
一怒之下,直接用Unity自己写个小插件实现这个小功能。
经测试,可实现根据某个窗口名称隐藏该窗口,但不适用窗口名称带中文的。可根据系统进程名称最小化窗口。
代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using WindowsHandler;
public class WindowMin : MonoBehaviour
{
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
// Start is called before the first frame update
void Start()
{
//以下为根据窗口名称隐藏窗口
IReadOnlyList<WindowInfo> list=WindowEnumerator.FindAll();
string mm="";
Tools.WriteTxt(Application.streamingAssetsPath+"/2.txt",mm);
for (int i = 0; i < list.Count; i++)
{
mm+="\n"+list[i].Title;
Debug.Log(list[i].Title);
}
Tools.WriteTxt(Application.streamingAssetsPath+"/2.txt",mm);
return;
//以下根据进程隐藏窗口
string str = Tools.LoadString(Application.streamingAssetsPath + "/1.txt");
//User32API.GetHandleByProcessName(str);
IntPtr a=FindWindow(null,str);
if(a!=IntPtr.Zero){
Application.Quit();
}
ShowWindow(a, 2);
// ShowWindow(GetForegroundWindow(), 2);
StartCoroutine(AA());
}
IEnumerator AA(){
yield return new WaitForSeconds(1);
Application.Quit();
}
// Update is called once per frame
void Update()
{
}
}
将代码随便挂在某个物体上,然后打包,在StreamingAssets文件夹的txt里面填入窗口名称或进程名称,运行即可。
相关工程链接及打包文件地址:https://download.csdn.net/download/qq_33155437/85444324