使用带参数的函数调用 [英] Use invoke on a function with a parameter

查看:78
本文介绍了使用带参数的函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c#程序,我把东西放在richtextbox中。每当文件更新时我都会更新它。然后我调用一个函数来为RTB的线条着色。我的问题是我需要在colorTextbox()函数上使用Invoke但我无法弄清楚如何使用它因为它使用了一个参数。

我对setupdatagrid()有类似的东西但是它不使用参数。

任何帮助将不胜感激。

谢谢

<前lang =c#> 使用系统;
使用 System.Collections.Generic;
使用 System.ComponentModel;
使用 System.Data;
使用 System.Drawing;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;
使用 System.Windows.Forms;
使用 System.Xml;
使用 System.IO;
使用 System.Security.Permissions;


namespace xml_reader
{

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

}

private void Form1_Load(< span class =code-keyword> object sender,EventArgs e)
{
richTextBox1.Multiline = true ;
// richTextBox1.AcceptsTab = true;
richTextBox1.SelectionColor = Color。红色;


}

private void btn_read_Click( object sender,EventArgs e)
{
OpenFileDialog openFileDialog1 = new 打开文件对话框();
// 设置过滤器选项和过滤器索引。
openFileDialog1.Filter = < span class =code-string> XML文件(* .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;
// 仅观看xml文件。
watcher.Filter = * .xml;

// 添加事件处理程序。
watcher.Changed + = new FileSystemEventHandler(OnChanged);
watcher.Created + = new FileSystemEventHandler(OnChanged);

// 开始观看。
// timer1.Enabled = true;
//
watcher.EnableRaisingEvents = true ;

}
}

private void OnChanged( object source,FileSystemEventArgs e)
{
// < span class =code-comment>指定更改,创建或删除文件时执行的操作。
string path = e 。完整路径;
Console.WriteLine( 文件: + path + + e.ChangeType);
System.Threading.Thread.Sleep( 1000 );
readXML(path);
}

private void readXML( string 文件名)
{
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 []行;
setupdatagrid();

const string title = POS PILOT LAPS ELAPSED SEED FAST LAP \ n;
StringBuilder builder = new StringBuilder(title, 1024 ); // 1k是一个公平的开始猜测; - )
using (XmlTextReader reader = new XmlTextReader(Filename))
{
// using语句确保读取器在完成后处于关闭状态。
(reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // 节点是一个元素。
if (reader.Name == 驱动程序
{
while (reader.MoveToNextAttribute()) // 读取属性。
{
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
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 ;
默认
break ;
}
}
row = new string [] {Pos ,飞行员,圈数,过去,种子,快速};
// dataGridView1.Rows.Add(row);

}
break ;
case XmlNodeType.Text: // 显示每个元素中的文字。
break ;
case XmlNodeType.EndElement: // 显示元素的结尾。
break ;
}
}
reader.Close();
}

// colorTextbox(linenumbers);

行动更新文本;
updateText =()= > richTextBox1.Text = builder.ToString();
if (richTextBox1.InvokeRequired)
richTextBox1.Invoke(updateText);
else
updateText();

}




private void colorTextbox( int 行)
{
if this .InvokeRequired)
{
this .Invoke( new 操作(()= > colorTextbox())); // 什么是正确的语法?
}
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 ]。长度;
richTextBox1.Select(start,length);
richTextBox1.SelectionBackColor = Color.LightGray;
}
如果(cb_DV.Checked == true
{
.Width = richTextBox1.Width;
this .Height = richTextBox1.Height + dataGridView1.Height + 17 ;
}
其他
{
.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 字体( 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 = 快速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 ; // 已过去
column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
column = dataGridView1.Columns [ 4 ];
column.Width = 70 ; // 种子
column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
column = dataGridView1.Columns [ 5 ];
column.Width = 110 ; // fast
column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
}

私有 void btn_font_Click( object sender,EventArgs e)
{
// 显示对话框。
FontDialog fontDialog1 = new FontDialog();
fontDialog1.Font = richTextBox1.Font;
fontDialog1.Color = richTextBox1.ForeColor;

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


}

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

// 将对话框的初始颜色设置为当前文本颜色。
colorDialog1.Color = richTextBox1.SelectionColor;

// 确定用户是否在对话框中单击确定并且颜色已更改。
if (colorDialog1.ShowDialog()== System.Windows.Forms.DialogResult.OK&&
colorDialog1。 Color!= richTextBox1.SelectionColor)
{
// 将选择颜色更改为指定的用户颜色。
richTextBox1.ForeColor = colorDialog1.Color;
}
}

私有 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);
}



}
}





我尝试了什么:



各种版本的语法

解决方案

为什么你需要使用反射和调用?



假设你已经使用反射获得了 MethodInfo ,你会使用:



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



假设你只输入一个参数。



阅读更多 MethodBase.Invoke Method(Object,Object [])(System.Reflection) [ ^ ]







Marc


我只能给你看一个VB片段;



 私有 委托  Sub  ColorTextBox_Dlg( Byval 作为  Int32 

< span class =code-keyword>公共 Sub ColorTextBox( Byval 作为 Int32
如果 .InvokeRequiered)然后
.Invoke( New ColorTextBox_Dlg( AddressOf ColorTextBox),行)
Else
' 免费使用,做你的好事
MsgBox(lines.ToString)
。关闭
结束 如果
结束 Sub

' 使用
ColorTextBox( 100


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

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

解决方案

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


I can only show you a VB snippet;

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)


这篇关于使用带参数的函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆