winforms 嵌入unity exe文件详细步骤

本文详细介绍了如何在WindowsForms应用中嵌入Unity生成的exe文件,包括创建WinForms项目、配置Unity、编写代码以管理和控制嵌入的exe、测试和调试,以及注意事项。
摘要由CSDN通过智能技术生成

要在WinForms中嵌入Unity生成的exe文件,可以按照以下步骤操作:

1. **创建WinForms项目**:在Visual Studio中创建一个新的Windows Forms应用程序项目,或者打开一个现有的项目。
2. **设计窗体布局**:在Form1中添加需要的控件,如Button、TableLayoutPanel和Panel,根据需求调整设计界面。

3. **配置Unity项目**:在Unity中创建一个新的场景或加载现有场景。然后选择“File”菜单中的“Build Settings”,选择“Windows Standalone”作为目标平台,并进行相应的设置。
4. **生成exe文件**:在Unity中构建项目,生成exe文件。
5. **编写代码**:在WinForms项目中添加新类,命名为exetowinform,详细代码如下

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    class exetowinform
    {

        EventHandler appIdleEvent = null;
        Control ParentCon = null;
        string strGUID = "";

        public exetowinform(Control C, string Titlestr)
        {
            appIdleEvent = new EventHandler(Application_Idle);
            ParentCon = C;
            strGUID = Titlestr;
        }

        /// <summary>  
        /// 将属性<code>AppFilename</code>指向的应用程序打开并嵌入此容器  
        /// </summary>  
        public IntPtr Start(string FileNameStr)
        {
            if (m_AppProcess != null)
            {
                Stop();
            }
            try
            {
                ProcessStartInfo info = new ProcessStartInfo(FileNameStr);
                info.UseShellExecute = true;
                info.WindowStyle = ProcessWindowStyle.Minimized;
                m_AppProcess = System.Diagnostics.Process.Start(info);
                m_AppProcess.WaitForInputIdle();
                Application.Idle += appIdleEvent;
            }
            catch
            {
                if (m_AppProcess != null)
                {
                    if (!m_AppProcess.HasExited)
                        m_AppProcess.Kill();
                    m_AppProcess = null;
                }
            }
            return m_AppProcess.Handle;
        }


        /// <summary>  
        /// 确保应用程序嵌入此容器  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        void Application_Idle(object sender, EventArgs e)
        {
            if (this.m_AppProcess == null || this.m_AppProcess.HasExited)
            {
                this.m_AppProcess = null;
                Application.Idle -= appIdleEvent;
                return;

            }

            Thread.Sleep(300);//这里加阻塞 ,时间可以大些
            Application.DoEvents();
            if (m_AppProcess.MainWindowHandle == IntPtr.Zero)
                return;
            Application.Idle -= appIdleEvent;
            EmbedProcess(m_AppProcess, ParentCon);
        }
        /// <summary>  
        /// 应用程序结束运行时要清除这里的标识  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        void m_AppProcess_Exited(object sender, EventArgs e)
        {
            m_AppProcess = null;
        }
        /// <summary>  
        /// 将属性<code>AppFilename</code>指向的应用程序关闭  
        /// </summary>  
        public void Stop()
        {
            if (m_AppProcess != null)// && m_AppProcess.MainWindowHandle != IntPtr.Zero)  
            {
                try
                {
                    if (!m_AppProcess.HasExited)
                        m_AppProcess.Kill();
                }
                catch (Exception)
                {
                }
                m_AppProcess = null;
            }
        }
        #region 属性  
        /// <summary>  
        /// application process  
        /// </summary>  
        Process m_AppProcess = null;

        /// <summary>  
        /// 标识内嵌程序是否已经启动  
        /// </summary>  
        public bool IsStarted { get { return (this.m_AppProcess != null); } }

        #endregion 属性  

        #region Win32 API  
        [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId", SetLastError = true,
             CharSet = CharSet.Unicode, ExactSpelling = true,
             CallingConvention = CallingConvention.StdCall)]
        private static extern long GetWindowThreadProcessId(long hWnd, long lpdwProcessId);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        [DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)]
        private static extern long GetWindowLong(IntPtr hwnd, int nIndex);

        public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, int dwNewLong)
        {
            if (IntPtr.Size == 4)
            {
                return SetWindowLongPtr32(hWnd, nIndex, dwNewLong);
            }
            return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
        }
        [DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]
        public static extern IntPtr SetWindowLongPtr32(HandleRef hWnd, int nIndex, int dwNewLong);
        [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", CharSet = CharSet.Auto)]
        public static extern IntPtr SetWindowLongPtr64(HandleRef hWnd, int nIndex, int dwNewLong);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern long SetWindowPos(IntPtr hwnd, long hWndInsertAfter, long x, long y, long cx, long cy, long wFlags);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);

        [DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)]
        private static extern bool PostMessage(IntPtr hwnd, uint Msg, uint wParam, uint lParam);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr GetParent(IntPtr hwnd);

        [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private const int SWP_NOOWNERZORDER = 0x200;
        private const int SWP_NOREDRAW = 0x8;
        private const int SWP_NOZORDER = 0x4;
        private const int SWP_SHOWWINDOW = 0x0040;
        private const int WS_EX_MDICHILD = 0x40;
        private const int SWP_FRAMECHANGED = 0x20;
        private const int SWP_NOACTIVATE = 0x10;
        private const int SWP_ASYNCWINDOWPOS = 0x4000;
        private const int SWP_NOMOVE = 0x2;
        private const int SWP_NOSIZE = 0x1;
        private const int GWL_STYLE = (-16);
        private const int WS_VISIBLE = 0x10000000;
        private const int WM_CLOSE = 0x10;
        private const int WS_CHILD = 0x40000000;

        private const int SW_HIDE = 0; //{隐藏, 并且任务栏也没有最小化图标}  
        private const int SW_SHOWNORMAL = 1; //{用最近的大小和位置显示, 激活}  
        private const int SW_NORMAL = 1; //{同 SW_SHOWNORMAL}  
        private const int SW_SHOWMINIMIZED = 2; //{最小化, 激活}  
        private const int SW_SHOWMAXIMIZED = 3; //{最大化, 激活}  
        private const int SW_MAXIMIZE = 3; //{同 SW_SHOWMAXIMIZED}  
        private const int SW_SHOWNOACTIVATE = 4; //{用最近的大小和位置显示, 不激活}  
        private const int SW_SHOW = 5; //{同 SW_SHOWNORMAL}  
        private const int SW_MINIMIZE = 6; //{最小化, 不激活}  
        private const int SW_SHOWMINNOACTIVE = 7; //{同 SW_MINIMIZE}  
        private const int SW_SHOWNA = 8; //{同 SW_SHOWNOACTIVATE}  
        private const int SW_RESTORE = 9; //{同 SW_SHOWNORMAL}  
        private const int SW_SHOWDEFAULT = 10; //{同 SW_SHOWNORMAL}  
        private const int SW_MAX = 10; //{同 SW_SHOWNORMAL}  

        #endregion Win32 API  

        /// <summary>  
        /// 将指定的程序嵌入指定的控件  
        /// </summary>  
        private void EmbedProcess(Process app, Control control)
        {
            // Get the main handle  
            if (app == null || app.MainWindowHandle == IntPtr.Zero || control == null) return;
            try
            {
                // Put it into this form  
                SetParent(app.MainWindowHandle, control.Handle);
            }
            catch (Exception)
            { }
            try
            {
                // Remove border and whatnot                 
                SetWindowLong(new HandleRef(this, app.MainWindowHandle), GWL_STYLE, WS_VISIBLE);
                SendMessage(app.MainWindowHandle, WM_SETTEXT, IntPtr.Zero, strGUID);
            }
            catch (Exception)
            { }
            try
            {
                // Move the window to overlay it on this window  
                MoveWindow(app.MainWindowHandle, 0, 0, control.Width, control.Height, true);
            }
            catch (Exception)
            { }
        }
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);

        const int WM_SETTEXT = 0x000C;
    }
}

在Form1_Load里面添加调用方法,代码如下

 private void Form1_Load_1(object sender, EventArgs e)
        {
            exetowinform fr = new exetowinform(panel12, "");
            //打开unity生成的exe文件
            fr.Start(@"C:\Users\ASUS\Downloads\Compressed\db800600\Mavlink.exe");
        }


6. **测试和调试**:运行WinForms应用程序,测试Unity exe文件是否正确嵌入并能够通过WinForms界面进行控制。


7. **发布应用程序**:在确保一切都工作正常后,可以发布你的WinForms应用程序。

需要注意的是,这个过程可能涉及到不同技术栈之间的交互,因此可能需要一定的技术知识和调试工作。如果在实现过程中遇到困难,可以参考相关的技术文章或者寻求专业的技术支持。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农校长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值