Unity3D:启动外部exe传参以及设置窗口位置和大小

大腿Plus 2019年5月29日11:08:36Unity3D之项目开发22,7581阅读模式

好久没有更新博客了,最近项目上没有太大的突破,也没有涉及到新东西,所以想写博客,但是无奈没有新东西,好在最近有点新的功能要做,之前也做过,但是并没有整理成博客,现在就记录一下。省的还要去百度找。(最近好像新的Unity版本不能破解了,官网有时候也上不去,不知道Unity要搞什么东东。)文章源自大腿Plus-https://www.shijunzh.com/archives/1142

今天要说的是Unity启动外部exe,并且传递参数,改变外部exe窗口位置以及窗口大小。启动exe这个百度搜一大堆,主要是怎么设置窗口位置及大小。窗口大小的方法Unity有自己的方法,但是位置就没法设置了,我今天用的方法是Windows原生的方法。需要引用user32.dll。废话不多说了,下面上代码。文章源自大腿Plus-https://www.shijunzh.com/archives/1142

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

public class ProperWindows : MonoBehaviour
{
    [DllImport("user32.dll")]
    static extern IntPtr SetWindowLong(IntPtr hWnd, int _nIndex, int dwNewLong);
    [DllImport("user32.dll")]
    static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow(); //获取最前端窗体句柄
    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    //[DllImport("user32.dll")]
    //static extern IntPtr GetWindowThreadProcessld(); 
    private void Awake()
    {
        //启动时传过来的string数组,下标为0的是启动的外部exe程序的完整路径,下标为1及之后的参数是想要传过来的参数。
        string[] args = Environment.GetCommandLineArgs();
        var winInfo = JsonUtility.FromJson<WinInfo>(args[1]);
        // 设置屏大小和显示位置
        SetWindowPos(GetForegroundWindow(), 0, winInfo.x, winInfo.y, winInfo.width, winInfo.height, 0x0040);
    }
    // Use this for initialization
    void Start()
    {
        //启动外部exe程序,第一个参数为exe完整路径,第二个参数为要传入的参数。
        string winInfo = JsonUtility.ToJson(new WinInfo(0, 0, 1000, 500));
        Process.Start(@"C:\Users\wangbo\Desktop\2\2.exe", winInfo);
    }

    // Update is called once per frame
    void Update()
    {

    }
}
[Serializable]
public class WinInfo
{
    public int x;
    public int y;
    public int width;
    public int height;
    
    public WinInfo(int x, int y, int width, int height)
    {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
}

上面的代码里我传的参数是json格式的,在Start里启动一个exe,在Awake里接收参数,设置窗口位置以及大小。有什么不懂的,可以随时联系我。文章源自大腿Plus-https://www.shijunzh.com/archives/1142

 文章源自大腿Plus-https://www.shijunzh.com/archives/1142

大腿Plus
  • 本文由 发表于 2019年5月29日11:08:36
  • 转载请务必保留本文链接:https://www.shijunzh.com/archives/1142

发表评论

评论:2   其中:访客  1   博主  1
    • 热情➹融化一切が
      热情➹融化一切が 0

      请问这个还有扩展吗?我现在需要在VR中显示出外部的exe画面

        • 大腿Plus
          大腿Plus

          @ 热情➹融化一切が 这个没有拓展,不过是可以实现的,如果这个exe是自己开发的可以实时的把画面用socket传输到VR内。具体方法可以谷歌或者百度。如果是第三方的,那就可能需要用直播流的方式,将exe画面直播录屏的方式,传输到VR内。