How to use Events in the Context of C#

Step 1 : Declare a delegate.
Step 2 : Create a class derived from System.EventArgs to encapsulate the event information.
Step 3 : Create the class that will raise the event. This class will have :
a) an event which will have the registered clients
b) a method to notify registered clients.
Step 4 : Create a client class. This class will have a method that matches the signature of the delegate. This method will receive the event.
Step 5 : Register this method with the event as being the authorized listener for the event.

Sample Code:

Step1: declare the delegate

 public delegate void FileFoundHandler(Object sender, FileFoundEventArgs e);

Step2:create a class derived from System.EventArgs

 using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

namespace MyTool

{

    class FileFoundEventArgs : EventArgs

    {

        private FileInfo fi;

        private int counter;

 

        public FileInfo FoundFile

        {

            get { return fi; }

        }

        public long CurrentCount

        {

            get { return counter; }

        }

        public FileFoundEventArgs(FileInfo fileinfo, int counterinfo)

        {

            fi = fileinfo;

            counter = counterinfo;

        }

    }

}

 

Step3-a: define your event

 public event FileFoundHandler FileFound;

 

Step3-b:define your methods which notifies the client(s)

        protected virtual void OnFileFound(FileInfo e)

        {

            if (FileFound != null)

            {

                //despatch the event to each client

                _count1++;

                FileFound(this, new FileFoundEventArgs(e, _count1));

            }

 

        }

 

Step4: client class

     namespace MyTool

{

    public partial class NBDocChecker : Form

    {

        private List<FileInfo> objFiles = null;

 

        public NBDocChecker()

        {

            InitializeComponent();

        }

 

..................

.............

 

Step5: hook the event to the listener method

                 FileFormater formater = new FileFormater(chc, this.txtPath.Text);

//register the listener method

            formater.FileFound += new FileFormater.FileFoundHandler(formater_FileFound);

//  register the listener method definition    

void formater_FileFound(object sender, FileFoundEventArgs e)

        {

            //throw new Exception("The method or operation is not implemented.");

            MyTool.CommonDelegate.RefreshUIHandler rdg=new MyTool.CommonDelegate.RefreshUIHandler(this.updateUI);

            this.Invoke(rdg, new Object[] { e.FoundFile.FullName, e.CurrentCount.ToString() });

        }

 

 

using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.IO;
using  Microsoft.Office.Interop.Excel;
using  System.Runtime.InteropServices;
using  log4net;

namespace  MyTool
{
    
class FileFormater
    
{

        
//private string _path;
        
//private string _pattern = "*.xls";
        
//private bool _recursive = true;
        ////private bool _removeReadOnly = true;
        private string _path = string.Empty;
        CheckCondition checkSpec 
= null;

        
private List<FileInfo> pendingFiles = new List<FileInfo>();
        
public List<FileInfo> ResultFiles
        
{
            
get return pendingFiles; }
        }

        
private int _count1 = 0;
        
private int _count2 = 0;

        
//private ILog logger = null;
        private ConfigHelper config = new ConfigHelper();

        
"Delegate Declaration"


        
"Events"

        
//delcare the methods which notify the clients
        protected virtual void OnFileFound(FileInfo e)
        
{
            
if (FileFound != null)
            
{
                
//despatch the event to each client
                _count1++;
                FileFound(
thisnew FileFoundEventArgs(e, _count1));
            }


        }

        
protected virtual void OnFileFoundEnd()
        
{
            
if (FileFondEnd != null)
            
{
                FileFondEnd(
this, _count1);
            }

        }



        
protected virtual void OnFileFormated(FileInfo e)
        
{
            
if (FileFormated != null)
            
{
                _count2
++;
                FileFormated(
thisnew FileFormatedEventArgs(e, _count2));
            }

        }


        
public FileFormater(CheckCondition condition, string path)
        
{
            
if (condition == nullthrow new ArgumentNullException("no condition specified");
            checkSpec 
= condition;
            _path 
= path;
            pendingFiles.Clear();
        }


        
public FileFormater()
        
{

        }


        
public List<FileInfo> FormatFiles()
        
{

            pendingFiles 
= GetFiles(_path, checkSpec.SearchPattern, checkSpec.Isrecursive);
            OnFileFoundEnd();

            
foreach (FileInfo item in pendingFiles)
            
{

               
if (Globals.Cancled)
               
{
                  
return pendingFiles;

               }

                processExcelFile(item);
                OnFileFormated(item);


            }

            clearUp();
            
//process file format
            return pendingFiles;
        }


        
//get all files need to be formated
        public  List<FileInfo> GetFiles(string path, string pattern, bool recursive)
        
{
            List
<FileInfo> resultFiles = new List<FileInfo>();

            DirectoryInfo baseDir 
= new DirectoryInfo(path);
            
if (Globals.Cancled)
            
{
                
//write log
                return resultFiles;
            }


            
try
            
{
                
if (recursive)
                
{
                    
foreach (DirectoryInfo di in baseDir.GetDirectories())
                    
{
                        GetFiles(di.FullName, pattern, recursive);

                    }

                }


                
//search files matched pattern
                FileInfo[] files = baseDir.GetFiles(pattern);
                
foreach (FileInfo fi in files)
                
{
                    
if (Globals.Cancled)
                    
{
                        
//write log
                        return resultFiles;
                    }

                    
//raise filefound event
                    OnFileFound(fi);
                }

                resultFiles.AddRange(files);
                pendingFiles.AddRange(files);

                
return pendingFiles;


            }

            
catch (Exception ex)
            
{
                System.Diagnostics.Debug.WriteLine(ex.Message);

                
return pendingFiles;
            }




        }


        Microsoft.Office.Interop.Excel.Application excel 
= new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook wb 
= null;
        
object missing = System.Reflection.Missing.Value;

        
private FileInfo processExcelFile(FileInfo file)
        
{


            
if (file.IsReadOnly)
            
{
                File.SetAttributes(file.FullName, FileAttributes.Normal);
                
            }


            
try
            
{
                
string pwd = config.OpenPWD;
                
try
                
{
                    wb 
= excel.Workbooks.Open(file.FullName, missing, false, missing, pwd, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                }

                
catch
                
{
                    Marshal.ReleaseComObject(wb);
                    excel.Quit();
                    Marshal.ReleaseComObject(excel);
                    excel 
= new Microsoft.Office.Interop.Excel.Application();
                    wb 
= excel.Workbooks.Open(file.FullName, missing, false, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                }

                
//set active sheet and active cell of sheet
                if (checkSpec.IsPagesetup)
                
{
                    
if (file.Name.IndexOf("夋柺崁栚掕媊彂">= 0)
                    
{
                        
for (int i = wb.Sheets.Count ; i >= 1; i--)
                        
{
                            
//((_Worksheet)xls).Activate();
                            _Worksheet sheet = (_Worksheet)wb.Worksheets[i];
                            sheet.Activate();
                            Microsoft.Office.Interop.Excel.Range range 
= sheet.get_Range("A1""A1");
                            range.Select();
                            
//apply page setting
                            if (sheet.Name.IndexOf("夋柺Event掕媊"< 0continue;
                            sheet.PageSetup.LeftMargin 
= excel.InchesToPoints(Convert.ToDouble(config.LeftMargin));
                            sheet.PageSetup.RightMargin 
= excel.InchesToPoints(Convert.ToDouble(config.RightMargin));
                            sheet.PageSetup.TopMargin 
= excel.InchesToPoints(Convert.ToDouble(config.TopMargin));
                            sheet.PageSetup.BottomMargin 
= excel.InchesToPoints(Convert.ToDouble(config.ButtomMargin));
                            sheet.PageSetup.HeaderMargin 
= excel.InchesToPoints(Convert.ToDouble(config.HeaderMargin));
                            sheet.PageSetup.FooterMargin 
= excel.InchesToPoints(Convert.ToDouble(config.FooterMargin));
                            sheet.PageSetup.Orientation 
= config.Orientation;
                            sheet.PageSetup.CenterHorizontally 
= config.CenterHorizontally;
                            sheet.PageSetup.CenterVertically 
= config.CenterVertically;
                            sheet.PageSetup.Zoom 
= config.Zoom;
                            excel.ActiveWindow.View 
= XlWindowView.xlPageBreakPreview;
                            excel.ActiveWindow.DisplayGridlines 
= true;

                        }


                    }

                    
else
                    
{
                        
for (int i = wb.Sheets.Count; i >= 1; i--)
                        
{
                            
//((_Worksheet)xls).Activate();
                            _Worksheet sheet = (_Worksheet)wb.Worksheets[i];
                            sheet.Activate();
                            Microsoft.Office.Interop.Excel.Range range 
= sheet.get_Range("A1""A1");
                            range.Select();
                            
//apply page setting
                            sheet.PageSetup.LeftMargin = excel.InchesToPoints(Convert.ToDouble(config.LeftMargin));
                            sheet.PageSetup.RightMargin 
= excel.InchesToPoints(Convert.ToDouble(config.RightMargin));
                            sheet.PageSetup.TopMargin 
= excel.InchesToPoints(Convert.ToDouble(config.TopMargin));
                            sheet.PageSetup.BottomMargin 
= excel.InchesToPoints(Convert.ToDouble(config.ButtomMargin));
                            sheet.PageSetup.HeaderMargin 
= excel.InchesToPoints(Convert.ToDouble(config.HeaderMargin));
                            sheet.PageSetup.FooterMargin 
= excel.InchesToPoints(Convert.ToDouble(config.FooterMargin));
                            sheet.PageSetup.Orientation 
= config.Orientation;
                            sheet.PageSetup.CenterHorizontally 
= config.CenterHorizontally;
                            sheet.PageSetup.CenterVertically 
= config.CenterVertically;
                            sheet.PageSetup.Zoom 
= config.Zoom;
                            excel.ActiveWindow.View 
= XlWindowView.xlPageBreakPreview;
                            excel.ActiveWindow.DisplayGridlines 
= true;
                        }

 
                    }


                     
                }


            }

            
finally
            
{
                
if (wb != null)
                
{
                    
//if (!wb.HasPassword)
                     wb.Password = config.OpenPWD;
                    wb.Save();
                    wb.Close(
truefalse, missing);
                    Marshal.ReleaseComObject(wb);

                }

                
if (excel != null)
                
{
                    excel.Quit();
                    GC.Collect();
                }

            }

            
return file;
        }


        
private void clearUp()
        
{
            
if (excel != null)
            
{
                excel.Quit();
                Marshal.ReleaseComObject(excel);
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }

        }



    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值