zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#程序窗体间使用回调事件方式通讯示例

c#事件程序 使用 方式 示例 通讯 回调
2023-06-13 09:15:13 时间

Form2:

复制代码代码如下:


//定义一个需要string类型参数的委托        
publicdelegatevoidMyDelegate(stringtext);        
publicpartialclassForm2:Form1    
   {        
      //定义该委托的事件    
       publiceventMyDelegateMyEvent;    
       publicForm2(stringtext)    
       {     
           InitializeComponent();    
           this.textBox1.Text=text;    
      }    
      privatevoidbtnChange_Click(objectsender,EventArgse)                  
      {    

          //触发事件,并将修改后的文本回传    
          MyEvent(this.textBox1.Text);    
          this.Close();    
       }    
  }

Form1:

复制代码代码如下:


publicpartialclassForm1:Form    
   {    
       publicintindex=0;    
       publicstringtext=null;    
       publicForm1()    
       {    
           InitializeComponent();    
       }    

       privatevoidlistBox1_SelectedIndexChanged(objectsender,EventArgse)    
       {    
           if(this.listBox1.SelectedItem!=null)    
           {    
               text=this.listBox1.SelectedItem.ToString();    
               index=this.listBox1.SelectedIndex;    
               Form2form2=newForm2(text);    

              //注册form2_MyEvent方法的MyEvent事件    
               form2.MyEvent+=newMyDelegate(form2_MyEvent);    
               form2.Show();    
           }    
       }    

      //处理    

       voidform2_MyEvent(stringtext)    
       {    
           this.listBox1.Items.RemoveAt(index);    
           this.listBox1.Items.Insert(index,text);    
      }    
  }