winform не появляется при запуске кода - PullRequest
0 голосов
/ 31 мая 2018

Я создаю быструю и грязную программу, которая в основном включает свет в моей комнате с веб-сайта в виде кода ката.во время программирования я решил временно использовать winform для тестирования вместо того, чтобы подсвечивать физическую лампочку (и там возникали всевозможные проблемы).но когда я запускаю свою программу, winform не отображается, я пытался запустить исполняемый файл, но все равно ничего.при отладке я вижу, что весь код работает нормально, просто не появляется winform.вот весь код:

form1.cs:

using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace alarm_light_test
{
    public partial class Form1 : Form
    {

        WebClient client = new WebClient();

        public Form1()
        {
            InitializeComponent();

            while (true)
            {
                if (CheckData())
                {
                    TurnSirenOn();
                    client.DownloadString("**link to .php file to reset the .txt file**");
                    Thread.Sleep(5000);
                    TurnSirenOff();
                }
                else
                {
                    Thread.Sleep(1000);
                }
            }
        }

    public bool CheckData()
        {
            bool retval = false;
            Stream stream = client.OpenRead("**link to online .txt file**");
            StreamReader reader = new StreamReader(stream);
            String content = reader.ReadToEnd();
            if(content == "1")
            {
                retval = true;
            }

            return retval;
        }

        public void TurnSirenOn()
        {
            pictureBox1.BackColor = Color.Green;
        }

        public void TurnSirenOff()
        {
            pictureBox1.BackColor = Color.Red;
        }
    }
}

program.cs:

using System;
using System.Windows.Forms;

namespace alarm_light_test
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Form1.Designer.cs

namespace alarm_light_test
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // pictureBox1
            // 
            this.pictureBox1.Location = new System.Drawing.Point(13, 13);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(235, 235);
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(260, 260);
            this.Controls.Add(this.pictureBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.PictureBox pictureBox1;
    }
}

1 Ответ

0 голосов
/ 31 мая 2018

В вашем конструкторе public Form1() у вас есть цикл навсегда (он же бесконечный цикл).

while(true) не даст конструктору завершить построение объекта формы и, следовательно, будетНевозможно отобразить что-либо.

public Form1()
{
    InitializeComponent();

    while (true) // This loop will never exit, and will run forever
    {
        ...
    }
}

Редактировать: Пример асинхронного запуска вашего кода, что позволяет форме полностью инициализироваться и отображаться в соответствии с ожиданиями.

public Form1()
{
    InitializeComponent();

    DoWorkAsynchronously();
}

private async Task DoWorkAsynchronously()
{
    await Task.Run(() =>
    {
        while (true)
        {
            if (CheckData())
            {
                TurnSirenOn();
                client.DownloadString("**link to .php file to reset the .txt file**");
                Thread.Sleep(5000);
                TurnSirenOff();
            }
            else
            {
                Thread.Sleep(1000);
            }
        }
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...