从另一个类中的事件更新表单控件

时间:2019-12-30 23:01:55

标签: c# multithreading event-handling

我是C#的初学者,也是我在这里的第一篇文章,所以请对我好:)

好吧,我正在尝试编写一个仅在文件更改后才读取文件的小应用程序,并在Windows窗体的richtextbox控件中更新新内容。

所以有我的代码:

public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                string path = @"C:\MyPath\";
                Filecheck NewFileChecker = new Filecheck();
                NewFileChecker.WatchingFile(path, "myFile.txt");
            }

这是我的Class FileCheck

class Filecheck
{
        public void WatchingFile (string FilePath, string Filter)
        {
            FileSystemWatcher fsw = new FileSystemWatcher();
            fsw.Path = FilePath;
            fsw.Filter = Filter;
            fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite;
            fsw.Changed += OnFileChange;
            fsw.EnableRaisingEvents = true;
        }


        private void OnFileChange(object sender, FileSystemEventArgs e)
        {
            string line;
            try
            {
                using (FileStream file = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (StreamReader sr = new StreamReader(file, Encoding.Default))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        MessageBox.Show(line);
                        // I WOULD LIKE TO UPDATE A FORM1 RichTextBox from here....
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

因此,我想从执行MessageBox方法的位置更新Windows窗体控件。有人知道我该怎么做吗?因为当我尝试这样调用时:

Form1.richTextBoxName.Invoke(new MethodInvoker(delegate
{
Form1.richTextBoxName.Text(line);
}));

好吧,我收到以下消息:“ CS0120:非静态字段,方法或属性需要对象引用”

有人知道我该如何解决? 谢谢

3 个答案:

答案 0 :(得分:1)

是的!对于我的想法Nguyen Van Thanh来说,这在我的项目中效果很好。但是我进行了一些修改,以使其能够帮助他人。.非常感谢您的投入。

在主要班级:

public Form1()
{
    string path = @"C:\MyPath\";            
    Filecheck NewFileChecker = new Filecheck();
    NewFileChecker.OnUpdateData += (d => UpdateRTBoxJournal(d));
    NewFileChecker.WatchingFile(path, "myFile.txt");
}

public void UpdateRTBoxJournal(string line)
{
    richTextBoxName.Invoke(new MethodInvoker(delegate
    {
    richTextBoxName.Text = line;
    }));
}

最后在另一个类的另一个文件中...

public delegate void UpdateData(string data);
class Filecheck
{
    public event UpdateData OnUpdateData;
    public void WatchingFile (string FilePath, string Filter)
    {
        FileSystemWatcher fsw = new FileSystemWatcher();
        fsw.Path = FilePath;
        fsw.Filter = Filter;
        fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite;
        fsw.Changed += OnFileChange;
        fsw.EnableRaisingEvents = true;
    }

    private void OnFileChange(object sender, FileSystemEventArgs e)
    {
        string line;
        try
        {
            using (FileStream file = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (StreamReader sr = new StreamReader(file, Encoding.Default))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    this.OnUpdateData?.Invoke(line);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Une erreur s'est produite." + ex.Message);
        }
    }
}

再次感谢您的回答。

答案 1 :(得分:0)

  1. 当您尝试使用Form1类时,它需要是新的。
  2. 如果要通过函数使用Form1,可以将Form1设置为“静态类型”。

答案 2 :(得分:0)

针对您的想法有很多解决方案,但我可以为您提供一种解决方案:

  

使用delegate

步骤1 :创建一个新的委托,其参数为01 stringreturn typevoid,名称为UpdateData

public delegate void UpdateData(string data);

第2步:声明event中创建的Filecheck中的class OnUpdateDatadelegate)中的public event UpdateData OnUpdateData;

this.OnUpdateData?.Invoke(line);

第3步:随时随地引发事件:

main

步骤4 :在您的OnUpdateData函数中,通过以下方式设置Filecheck NewFileChecker = new Filecheck(); NewFileChecker.OnUpdateData += (d => MessageBox.Show(d));

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public delegate void UpdateData(string data);
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string path = @"C:\MyPath\";
            Filecheck NewFileChecker = new Filecheck();
            NewFileChecker.OnUpdateData += (d => MessageBox.Show(d));
            NewFileChecker.WatchingFile(path, "myFile.txt");
        }
    }
    class Filecheck
    {
        public event UpdateData OnUpdateData;
        public void WatchingFile(string FilePath, string Filter)
        {
            FileSystemWatcher fsw = new FileSystemWatcher();
            fsw.Path = FilePath;
            fsw.Filter = Filter;
            fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite;
            fsw.Changed += OnFileChange;
            fsw.EnableRaisingEvents = true;
        }


        private void OnFileChange(object sender, FileSystemEventArgs e)
        {
            string line;
            try
            {
                using (FileStream file = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (StreamReader sr = new StreamReader(file, Encoding.Default))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        //MessageBox.Show(line);
                        // I WOULD LIKE TO UPDATE A FORM1 RichTextBox from here....
                        this.OnUpdateData?.Invoke(line);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

完整代码:

WithEvents