Click here to Skip to main content
15,921,530 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a c# program where I put stuff in a richtextbox. I update it whenever the file is updated. Then I call a function to color the lines of the RTB. My issue is that I need to use Invoke on the colorTextbox() function but I can't figure out how to do it because it uses a parameter.
I have a similar thing for setupdatagrid() but it does not use a parameter.
Any help will be greatly appreciated.
Thanks
C#
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.Xml;
using System.IO;
using System.Security.Permissions;


namespace xml_reader
{
 
    public partial class Form1 : Form
    {
        string filename;
        public Form1()
        {
            InitializeComponent();
            setupdatagrid();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            richTextBox1.Multiline = true;
           // richTextBox1.AcceptsTab = true;
            richTextBox1.SelectionColor = Color.Red; 
            
            
        }

        private void btn_read_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            // Set filter options and filter index.
            openFileDialog1.Filter = "XML Files (*.xml)|*.xml";
            openFileDialog1.FilterIndex = 1;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                filename = openFileDialog1.FileName;
                readXML(openFileDialog1.FileName);
              
                FileSystemWatcher watcher = new FileSystemWatcher();
                string directoryName = Path.GetDirectoryName(openFileDialog1.FileName);
                watcher.Path = directoryName;
                watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                // Only watch xml files.
                watcher.Filter = "*.xml";

                // Add event handlers.
                watcher.Changed += new FileSystemEventHandler(OnChanged);
                watcher.Created += new FileSystemEventHandler(OnChanged);

                // Begin watching.
    //            timer1.Enabled = true;
                //  or
              watcher.EnableRaisingEvents = true;
                
            }  
        }

        private  void OnChanged(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted.
            string path = e.FullPath;
            Console.WriteLine("File: " + path + " " + e.ChangeType);
            System.Threading.Thread.Sleep(1000);
            readXML(path);
        }

        private void readXML(string Filename)
        {
          int linenumbers = 0;
          string stringvalue;
          string Pos = "POS";
          string Pilot = "PILOT";
          string laps = "LAPS";
          string elapsed = "ELAPSED";
          string seed = "SEED";
          string fast = "FAST LAP";
          string[] row;
          setupdatagrid();

          const string title = "POS           PILOT                 LAPS    ELAPSED      SEED         FAST LAP \n";
          StringBuilder builder = new StringBuilder(title, 1024); // 1k is a fair starting "guess" ;-)
          using (XmlTextReader reader = new XmlTextReader(Filename))
          {
            // The using statement ensures that reader is Closed when done.
            while (reader.Read())
            {
              switch (reader.NodeType)
              {
              case XmlNodeType.Element: // The node is an element.
                if (reader.Name == "Driver")
                {
                  while (reader.MoveToNextAttribute()) // Read the attributes.
                  {
                    stringvalue = reader.Value;
                    switch (reader.Name)
                    {
                    case "position":
                      builder.Append(" ").Append(stringvalue).Append("\t");
                      Pos = stringvalue;
                      break;
                    case "name":
                      string longname = stringvalue.PadRight(30);
                      Console.WriteLine("{0} {1}", longname, longname.Length);
                      builder.Append(longname);
                      Pilot = stringvalue;
                      break;
                    case "laps":
                      if (string.IsNullOrWhiteSpace(stringvalue))
                        stringvalue = "0";
                      builder.Append("  ").Append(stringvalue).Append("\t\t");
                      laps = stringvalue;
                      break;
                    case "seed":
                      if (string.IsNullOrWhiteSpace(stringvalue))
                        stringvalue = "0.000";
                      builder.Append(stringvalue).Append("\t\t");
                      seed = stringvalue;
                      break;
                    case "elapsedTime":
                      if (string.IsNullOrWhiteSpace(stringvalue))
                        stringvalue = "0.000";
                      builder.Append(" ").Append(stringvalue).Append("\t\t");
                      elapsed = stringvalue;
                      break;
                    case "fastLap":
                      if (string.IsNullOrWhiteSpace(stringvalue))
                        stringvalue = "0.000";
                      stringvalue = stringvalue.PadRight(8);
                      builder.Append(" ").AppendLine(stringvalue);
                      fast = stringvalue;
                      linenumbers++;
                      break;
                    default:
                      break;
                    }
                  }
                  row = new string[] { Pos, Pilot, laps, elapsed, seed, fast };
 //                 dataGridView1.Rows.Add(row);

                }
                break;
              case XmlNodeType.Text: //Display the text in each element.
                break;
              case XmlNodeType.EndElement: //Display the end of the element.
                break;
              }
            }
            reader.Close();
          }

          //          colorTextbox(linenumbers);

          Action updateText;
          updateText = () => richTextBox1.Text = builder.ToString();
          if (richTextBox1.InvokeRequired)
              richTextBox1.Invoke(updateText);
          else
              updateText();
            
  }



        
        private void colorTextbox(int lines)
        {
             if (this.InvokeRequired)
            {
              this.Invoke(new Action(() => colorTextbox()));// what is the correct Syntax?
            }
            else
            {

                int lineNumberToSelect = 0;
                int start = richTextBox1.GetFirstCharIndexFromLine(lineNumberToSelect);
                int length = richTextBox1.Lines[lineNumberToSelect].Length;
                richTextBox1.Select(start, length);
                richTextBox1.SelectionBackColor = Color.Red;
                for (int i = 1; i <= lines; i += 2)
                {
                    lineNumberToSelect = i;
                    start = richTextBox1.GetFirstCharIndexFromLine(i);
                    length = richTextBox1.Lines[i].Length;
                    richTextBox1.Select(start, length);
                    richTextBox1.SelectionBackColor = Color.Gray;

                    start = richTextBox1.GetFirstCharIndexFromLine(i + 1);
                    length = richTextBox1.Lines[i + 1].Length;
                    richTextBox1.Select(start, length);
                    richTextBox1.SelectionBackColor = Color.LightGray;
                }
                if (cb_DV.Checked == true)
                {
                    this.Width = richTextBox1.Width;
                    this.Height = richTextBox1.Height + dataGridView1.Height + 17;
                }
                else
                {
                    this.Width = richTextBox1.Width;
                    this.Height = richTextBox1.Height + 17;
                }
            }
        }

        private void setupdatagrid()
        {

            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => setupdatagrid()));
            }
            else
            {
                dataGridView1.Rows.Clear();
                dataGridView1.ColumnCount = 6;
                foreach (DataGridViewColumn c in dataGridView1.Columns)
                {
                    c.DefaultCellStyle.Font = new Font("Courrier New", 14F, FontStyle.Bold);
                }

                dataGridView1.Columns[0].Name = "POS";
                dataGridView1.Columns[1].Name = "PILOT";
                dataGridView1.Columns[2].Name = "LAPS";
                dataGridView1.Columns[3].Name = "ELAPSED";
                dataGridView1.Columns[4].Name = "SEED";
                dataGridView1.Columns[5].Name = "FAST LAP";
                dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Red;
                dataGridView1.EnableHeadersVisualStyles = false;

                DataGridViewColumn column = dataGridView1.Columns[0];
                column.Width = 40;//POS
                column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                column = dataGridView1.Columns[1];
                column.Width = 350;//PILOT
                column = dataGridView1.Columns[2];
                column.Width = 50;//laps
                column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                column = dataGridView1.Columns[3];
                column.Width = 90;//elapsed
                column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                column = dataGridView1.Columns[4];
                column.Width = 70;//seed
                column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                column = dataGridView1.Columns[5];
                column.Width = 110;//fast
                column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }
        }

        private void btn_font_Click(object sender, EventArgs e)
              {
                  // Show the dialog.
                  FontDialog fontDialog1 = new FontDialog();
                  fontDialog1.Font = richTextBox1.Font;
                  fontDialog1.Color = richTextBox1.ForeColor;

                  if (fontDialog1.ShowDialog() != DialogResult.Cancel)
                  {
                      richTextBox1.Font = fontDialog1.Font;
                      richTextBox1.ForeColor = fontDialog1.Color;
                  }


              }

            private void btncolor_Click(object sender, EventArgs e)
            {
                ColorDialog colorDialog1 = new ColorDialog();

                // Set the initial color of the dialog to the current text color.
                colorDialog1.Color = richTextBox1.SelectionColor;

                // Determine if the user clicked OK in the dialog and that the color has changed.
                if (colorDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
                   colorDialog1.Color != richTextBox1.SelectionColor)
                {
                    // Change the selection color to the user specified color.
                    richTextBox1.ForeColor = colorDialog1.Color;
                }
            }

            private void richTextBox1_ContentsResized(object sender, ContentsResizedEventArgs e)
            {
                richTextBox1.Height = e.NewRectangle.Height;
            }

            private void timer1_Tick(object sender, EventArgs e)
            {
                Console.WriteLine("timer tick");
                readXML(filename);
            }

              

    }
}


What I have tried:

various versions of the syntax
Posted
Updated 19-Jun-16 12:53pm

Why do you need to use reflection and Invoke?

Assuming you have acquired the MethodInfo using reflection, you would use:

method.Invoke(yourObject, new object[] {parm1})

Assuming you are only passing in one parameter.

Read more MethodBase.Invoke Method (Object, Object[]) (System.Reflection)[^]

.

Marc
 
Share this answer
 
v2
Comments
BillWoodruff 20-Jun-16 0:05am    
+5
Matt T Heffron 21-Jun-16 12:03pm    
Marc, This question is a follow up from OP's previous question at http://www.codeproject.com/Questions/1107199/Confused-about-static and the discussion following my Solution there.
OP's is using the System.Windows.Forms.Control.Invoke to update the UI across threads.
Member 3652617 21-Jun-16 15:11pm    
Thanks Marc, but I still don't get how to do it. I tried different versions of
this.Invoke(colorTextbox(), new object[] { lines });

but can't figure it out.
I can only show you a VB snippet;

VB
Private Delegate Sub ColorTextBox_Dlg(Byval lines As Int32)

Public Sub ColorTextBox(Byval lines As Int32)
   If (Me.InvokeRequiered) Then
       Me.Invoke(New ColorTextBox_Dlg(AddressOf ColorTextBox), lines) 
   Else
       'FREE ACCES, DO YOUR STUFF
       MsgBox(lines.ToString)
       Me.Close
   End If
End Sub

'Use
ColorTextBox(100)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900