c#如何在每次文本更改时动态创建的文本框中添加文本行

时间:2016-11-14 16:19:45

标签: c# textbox filesystemwatcher

我正在使用FileSystemWatcher观看文件文本以进行任何更改,并在文本框中显示其数据,并在更改完成后通过将表单颜色更改为红色并发出哔声来提醒用户;当用户在文本框内单击时,颜色变为正常。

这是我的第一次尝试,它运作良好:

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 System.IO;
using System.Media;

namespace Breacking_News
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
        {
            string file_name = ("\\\\172.200.10.5\\txt\\عاجل.txt");
            FileStream logFileStream = new FileStream(file_name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            StreamReader logFileReader = new StreamReader(logFileStream);
            while (!logFileReader.EndOfStream)
            {
                string news = logFileReader.ReadToEnd();
                textBox1.Text = news.Replace(System.Environment.NewLine, "\r\n ************************************************ \r\n");
                infoText.Text = ("Last update at : " + DateTime.Now);
            }

            // Clean up
            logFileReader.Close();
            logFileStream.Close();
        }

        private void textBox1_Click(object sender, EventArgs e)
        {
            this.BackColor = DefaultBackColor;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            //FormWindowState.Normal = true;
            this.BackColor = System.Drawing.Color.Red;
            System.Media.SystemSounds.Beep.Play();
        }
    }
}

现在我想对此进行改进,以便每行都显示在单独的文本框中。知道我不知道文本文件包含多少行,我将使用此代码动态创建TextBox。

我单独测试了这段代码并且运行正常。每行显示在一个文本框中:

string file_name = ("\\\\172.200.10.5\\txt\\عاجل.txt");
var linecount = File.ReadLines(file_name).Count();
TextBox[] txtBoxes = new TextBox[linecount];
for (int i = 0; i < txtBoxes.Length; i++)
{
    string[] lines = File.ReadAllLines(file_name);
    var txt = new TextBox();
    txtBoxes[i] = txt;
    txt.Name = ("TextBox" + i);
    txt.Text = lines.ElementAtOrDefault(i);
    txt.Location = new Point(50, 32 + (i * 110));
    txt.Visible = true;
    txt.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
    txt.Multiline = true;
    txt.ReadOnly = true;
    txt.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
    txt.Size = new System.Drawing.Size(440, 100);
    this.Controls.Add(txt);
}

问题是当我从第一个代码插入第二个方法到while循环时:

while (!logFileReader.EndOfStream)

运行程序时,会为第一次文本更改动态创建文本框。但是当文本文件发生新的更改时,创建的文本框不会进行更改。

0 个答案:

没有答案