如何在类中实例化一个表单?

时间:2017-07-17 18:29:29

标签: c#

我需要使用class" Camera"在窗体中,但发生以下错误:

  

System.TypeInitializationException:'类型初始值设定项   ' VideoRecognition.NeorisForm'抛出异常。'

NeorisForm.css

https://company.com/subfolder/index.php

Camera.css

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 VideoRecognition.FRAMEWORKS.AForge.Camera;

namespace VideoRecognition
{
    public partial class NeorisForm : Form
    {

        private static Camera AForgeCamera = new Camera();

        public NeorisForm()
        {
            InitializeComponent();
            AForgeCamera.BuscarDispositivos();
        }



        private void NeorisForm_Load(object sender, EventArgs e) {

        }

        private void btn_IniciarCamera_Click(object sender, EventArgs e)
        {
            AForgeCamera.LigarCamera();
        }

        private void btn_PararVideo_Click(object sender, EventArgs e)
        {
            AForgeCamera.DesligarCamera();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

为了获得我认为你期望的结果,在Camera类上创建一个带有NeorisForm的构造函数,然后在创建Camera时传递对表单的引用。像这样......

在NeorisForm类上,将摄像头声明更改为:

private static Camera AForgeCamera;

在Camera类上,将NeorisForm声明更改为:

private static NeorisForm formPrincipal;

并添加一个Camera Constructor,如下所示:

public Camera(NeorisForm form)
{
    formPrincipal = form;
}

然后在NeorisForm构造函数中实例化Camera,如下所示:

public NeorisForm()
{
    InitializeComponent();
    AForgeCamera = new Camera(this);
    AForgeCamera.BuscarDispositivos();
}

我必须承认使用这样的静态变量,基本上将这两个类绑定在一起,会让我有点紧张(并降低了类的实用性),但我会假设你有一些独特的要求,需要这种关系。

祝你好运!