Переключите светодиод на форме, вызвав переменную, присутствующую в другой форме - PullRequest
0 голосов
/ 27 февраля 2019

У меня есть две формы (форма 1 и форма 2).Form1 позволяет вам просматривать выходные данные камеры на экране (рисуя растровое изображение), что позволяет отслеживать пользователя, если он находится на расстоянии поиска от камеры.Также в Form1 нарисован вид Led, который инициализируется красным, и когда он рисует скелет пользователя, то светодиод становится зеленым.(И это нормально для меня)

Form2 состоит из панели и кнопок (среди них есть кнопка, которая, при нажатии, заставляет Form1 появляться на панели Form2).Кроме того, Form2 также содержит Led, инициализированный красным, но который должен стать зеленым в соответствии с той же логикой Form1.Но я не могу этого сделать.Я попытался создать статический открытый класс, содержащий статическую логическую переменную, которая может использоваться обеими формами, но не работает одинаково.

    public class Program
    {
        static public void Main()
        {
            Console.CancelKeyPress += delegate {
                Nuitrack.Release();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            };

            try
            {


                Application.Run(new Form2());
                //Application.Run(new MainForm());

            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
            }
        }
    }

public static class Led
{
    public static bool isGreen;
}

public class SkeletonData
    {
        protected int numJoints;
        protected ulong timestamp;

        public SkeletonData();

        public int NumUsers { get; set; }
        public Skeleton[] Skeletons { get; set; }
        public ulong Timestamp { get; }
        protected int numUsers { get; set; }
        protected Skeleton[] skeletons { get; set; }

        public Skeleton GetSkeletonByID(int id);
    }

public class Form1 : Form
{
public SkeletonData _skeletonData;
public SkeletonTracker _skeletonTracker;

    protected override void OnPaint(PaintEventArgs args)
    {
        base.OnPaint(args);
         try
            {
                Nuitrack.Update(_skeletonTracker);
            }
            catch (LicenseNotAcquiredException exception)
            {
                Console.WriteLine("LicenseNotAcquired exception. Exception: ", exception);
                throw exception;
            }
            catch (Exception exception)
            {
                Console.WriteLine("Nuitrack update failed. Exception: ", exception);
            }
        // Draw a bitmap
        args.Graphics.DrawImage(_bitmap.Bitmap, new Point(0, 0));

        // Draw LED
        Pen blackPen = new Pen(Color.Black, 5);
        args.Graphics.DrawEllipse(blackPen, 565, 403, 50, 50);

        //LED initialized to red
        args.Graphics.FillEllipse(Brushes.Red, 565, 403, 50, 50);

        Led.isGreen = false;   

        if (_skeletonData != null)
        {
            foreach (var skeleton in _skeletonData.Skeletons)
            {
                //LED turns green                  
                args.Graphics.FillEllipse(Brushes.Green, 565, 403, 50, 50);
                Led.isGreen = true;
            }
        }
    }
}

public class Form2 : Form
    {
        private System.ComponentModel.IContainer components = null;
        private bool flag;
        private bool dataon;
        private bool pause;
        private Thread t1;

        public SkeletonData _skeletonDataX;
        public SkeletonTracker _skeletonTrackerX;
        public bool semX;

        private bool isGreen;

        public FormPrincipale()
        {
            InitializeComponent();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.btnShow = new System.Windows.Forms.Button();
            this.btnDati = new System.Windows.Forms.Button();
            this.btnHide = new System.Windows.Forms.Button();
            this.btnPause = new System.Windows.Forms.Button();
            this.btnExit = new System.Windows.Forms.Button();
            this.panel1 = new System.Windows.Forms.Panel();
            this.SuspendLayout();
            // 
            // btnStart
            // 
            this.btnShow.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnShow.Location = new System.Drawing.Point(25, 520);
            this.btnShow.Name = "btnStart";
            this.btnShow.Size = new System.Drawing.Size(75, 23);
            this.btnShow.TabIndex = 0;
            this.btnShow.Text = "SHOW";
            this.btnShow.UseVisualStyleBackColor = true;
            this.btnShow.Click += new System.EventHandler(this.btnShow_Click);
            //
            //btnDati
            //
            this.btnDati.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnDati.Location = new System.Drawing.Point(125, 520);
            this.btnDati.Name = "btnBitMap";
            this.btnDati.Size = new System.Drawing.Size(75, 23);
            this.btnDati.TabIndex = 3;
            this.btnDati.Text = "DATA";
            this.btnDati.UseVisualStyleBackColor = true;
            this.btnDati.Click += new System.EventHandler(this.btnDati_Click);
            //
            //btnHide
            //
            this.btnHide.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnHide.Location = new System.Drawing.Point(225, 520);
            this.btnHide.Name = "btnHide";
            this.btnHide.Size = new System.Drawing.Size(75, 23);
            this.btnHide.TabIndex = 3;
            this.btnHide.Text = "HIDE";
            this.btnHide.UseVisualStyleBackColor = true;
            this.btnHide.Click += new System.EventHandler(this.btnHide_Click);
            //
            //btnPause
            //
            this.btnPause.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnPause.Location = new System.Drawing.Point(325, 520);
            this.btnPause.Name = "btnHide";
            this.btnPause.Size = new System.Drawing.Size(75, 23);
            this.btnPause.TabIndex = 3;
            this.btnPause.Text = "PAUSE";
            this.btnPause.UseVisualStyleBackColor = true;
            this.btnPause.Click += new System.EventHandler(this.btnPause_Click);
            //
            //btnExit
            //
            this.btnExit.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnExit.Location = new System.Drawing.Point(425, 520);
            this.btnExit.Name = "btnStop";
            this.btnExit.Size = new System.Drawing.Size(75, 23);
            this.btnExit.TabIndex = 3;
            this.btnExit.Text = "EXIT";
            this.btnExit.UseVisualStyleBackColor = true;
            this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
            //
            // panel1
            // 
            this.panel1.BackColor = System.Drawing.SystemColors.ControlLightLight;
            this.panel1.Location = new System.Drawing.Point(12, 12);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(650, 495);
            this.panel1.TabIndex = 2;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(680, 560);
            this.Controls.Add(this.panel1);
            this.Controls.Add(this.btnShow);
            this.Controls.Add(this.btnDati);
            this.Controls.Add(this.btnHide);
            this.Controls.Add(this.btnPause);
            this.Controls.Add(this.btnExit);
            this.Name = "Form1";
            this.Text = "MyNuiTrack";
            this.ResumeLayout(false);
         }

        private System.Windows.Forms.Button btnShow;
        private System.Windows.Forms.Button btnDati;
        private System.Windows.Forms.Button btnHide;
        private System.Windows.Forms.Button btnPause;
        private System.Windows.Forms.Button btnExit;
        private System.Windows.Forms.Panel panel1;
        MainForm frm = new MainForm(); 

       // private static ManualResetEvent _mre = new ManualResetEvent(false);
        private static EventWaitHandle _mre = new ManualResetEvent(initialState: true);

        private void MyThreadMethod1()
        {
            EventArgs e = new EventArgs();
            while (flag)
            {
                frm.OttieniDati(e);
                Thread.Sleep(50);
                _mre.WaitOne();
            }
        }

        private void btnShow_Click(object sender, EventArgs e)
        {
            flag = true;
            frm.TopLevel = false;
            this.panel1.Controls.Add(frm);
            frm.Location = new System.Drawing.Point(6, 6);
            frm.ControlBox = false;
            frm.Show();
            btnPause.Enabled = false; btnDati.Enabled = true;
        }

        private void btnDati_Click(object sender, EventArgs e)
        {
            t1 = new Thread(new ThreadStart(MyThreadMethod1));
            t1.Start();
            dataon = true;
           _mre.Set();

            if (pause = true)
            {
                btnPause.Enabled = true; btnDati.Enabled = false;
                _mre.Set();
            }
        }

        private void btnHide_Click(object sender, EventArgs e)
        {
            frm.Visible = false;
            btnPause.Enabled = true;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (dataon==true || pause==true)
            {
                if (t1.IsAlive)
                {
                    t1.Abort();
                    _mre.Close();
                }
            }
            this.Close();
            //Application.Exit();
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            btnPause.Enabled = false; btnDati.Enabled = true;
            _mre.Reset();
            pause = true;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Pen blackPen = new Pen(Color.Black, 5);
            e.Graphics.DrawEllipse(blackPen, 615, 513, 40, 40);
            e.Graphics.FillEllipse(Brushes.Red, 615, 513, 40, 40);

            if (this.isGreen)
            {
                e.Graphics.FillEllipse(Brushes.Green, 615, 513, 40, 40);
            }
        }
    }

1 Ответ

0 голосов
/ 28 февраля 2019

Вы можете вызвать событие из формы Form1, назовем его «OnLedChanged» всякий раз, когда светодиод меняет состояние.Затем Form2 может зарегистрироваться на это событие в Form1.

Когда индикатор изменится на Form1, Form2 будет уведомлен и будет действовать соответственно.

Form1

using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public delegate void OnLedChangedEventHandler(object sender, LedEventArgs e);

        public event OnLedChangedEventHandler OnLedChanged;

        public class LedEventArgs : EventArgs
        {
            public bool IsGreen { get; set; }
        }

        public Form1()
        {
            InitializeComponent();

            var form2 = new Form2(this);
            form2.Show();
        }

        private void ChangeLedState(bool status)
        {
            if (null != OnLedChanged) OnLedChanged(this, new LedEventArgs { IsGreen = status });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ChangeLedState(true);
        }
    }
}

Form2

using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form2 : Form
    {
        private bool isGreen;

        public Form2(Form1 form1)
        {
            form1.OnLedChanged += (object sender, Form1.LedEventArgs e) =>
            {
                this.isGreen = e.IsGreen;
                this.Refresh();                
            };
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Pen blackPen = new Pen(Color.Black, 5);
            e.Graphics.DrawEllipse(blackPen, 10, 10, 40, 40);
            e.Graphics.FillEllipse(Brushes.Red, 10, 10, 40, 40);

            if (this.isGreen)
            {
                e.Graphics.FillEllipse(Brushes.Green, 10, 10, 40, 40);
            }
        }
    }
}

Form2 необходим доступ к экземпляру Form1 (в моем примере я передаю его в конструктор Form2).

Надеюсь, это поможет:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...