Используйте вызывается функция с параметром
У меня есть программа на c#, где я помещаю вещи в richtextbox. Я обновляю его всякий раз, когда файл обновляется. Затем я вызываю функцию для окрашивания линий RTB. Моя проблема заключается в том, что мне нужно использовать Invoke для функции colorTextbox (), но я не могу понять, как это сделать, потому что она использует параметр.
У меня есть аналогичная вещь для setupdatagrid (), но она не использует параметр.
Любая помощь будет очень признательна.
Спасибо
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); } } }
Что я уже пробовал:
различные варианты синтаксиса