XuanchenLin/NanUI

在 NanUI 使用 WinForm 的原生窗体作为主窗体

Closed this issue · 2 comments

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using NetDimension.NanUI;
using System.Diagnostics;
namespace WindowsFormsApp1
{
    class Program
    {
        static void Main()
        {
            // ...
           

            Process[] ps = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
            if (ps.Length > 1)   //注意:使用>1是对的,因为当前判断时,已经是已启动的第二个程序
            {
                MessageBox.Show("程序已启动,它可能已被最小化为任务栏图标。");
                Environment.Exit(1);
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form2());

        }
    }
}



Form2.cs
``

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NetDimension.NanUI;
namespace WindowsFormsApp1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
             WinFormium.CreateRuntimeBuilder(env => {

              env.CustomCefSettings(settings =>
              {
                  // 在此处设置 CEF 的相关参数
              });

              env.CustomCefCommandLineArguments(commandLine =>
              {
                  // 在此处指定 CEF 命令行参数
              });

          }, app =>
          {
              // 指定启动窗体
              app.UseMainWindow(context => new MainWindow());
          })
          .Build()
          .Run();
        }

        private void chart2_Click(object sender, EventArgs e)
        {

        }

        private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}

program.cs调用 Form2.cs form2.cs调用NanUi,报错如下:

在单个线程上开始另一个消息循环是无效操作。请改用 Form.ShowDialog

image

NanUI 需要执行自己单独的进程,所以不能在程序启动后再初始化。换句话来说,NanUI 已经封装了 WinForm 应用程序启动的流程。

如果只是希望实现远程窗体启动后再使用 NanUI 的 Formium 窗体,那么还是需要遵循 NanUI 的启动过程,只需要在 UseMainWindow 方法里使 ApplicationContext 的 MainForm 属性指向原生 WinForm 窗体即可。

例如项目中有:
Program.cs - 启动入口
Form1.cs - WinForm 窗体
FormiumWindow - NanUI 窗体

那么 Main 方法中依然使用 NanUI 的初始化方法:

WinFormium.CreateRuntimeBuilder(app=>{
    app.UseMainWindow(ctx=>{
        ctx.MainForm = new Form1();
        return null;
    });
});

这样就可以实现使用原生窗体 Form1 作为主窗体,然后再从 Form1 启动 NanUI 的任意窗体。