码迷,mamicode.com
首页 > 其他好文 > 详细

C#邮件接收系统核心代码(接收POP3邮件IMAP邮件)

时间:2014-06-10 11:19:19      阅读:1209      评论:0      收藏:0      [点我收藏+]

标签:des   c   style   class   blog   code   

/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2013/11/18
 * Time: 20:55
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Collections; 
using System.Text;


using LumiSoft.Net;
using LumiSoft.Net.Log;
using LumiSoft.Net.MIME;
using LumiSoft.Net.Mail;
using LumiSoft.Net.IMAP;
using LumiSoft.Net.IMAP.Client;
using LumiSoft.Net.POP3.Client;

//热键
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Collections.Generic;


//sqlite数据库驱动组件
using System.Data.SQLite;

//多线程
using System.Threading;

//MD5加密
using System.Security.Cryptography;

using System.Diagnostics;

using CS;

namespace mail
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	///

	//主函数类
	public partial class MainForm : Form
	{	
		Hook m_hook = new Hook();

		public static string thisuser="";
		public static int threadstate=0;
		 private IMAP_Client m_pImap = null;
		 public static string PREmail="";
		 public static string PRPro="";
		 public static ArrayList list = new ArrayList();
		 public class client
		 {
			public string ip;
			public string usr;
			public string pass;
			public string serverport;
			public int port;
			public string ssl;
			public string pro;
		 	public int time;
		 	public int DEAD;
		 }
		 public static string global_user="";
		 public static string folder="";
		 public static int global_type=1;
		 //邮件账户书目
		 public static int num=0;
		 static client[] zhanghu=new client[10];
		 //有效账号
		 public static int mail_able=0;
		 public static int mail_unable=0;
		 
		 //邮件总数目
		 public static int emlnum=0;
		 
		 //自动收信总时间
		 public string auto;
		 
		 //imap收信起始时间
		 public static string imap_start;
		 public static string imap_end;
		 
		 //IMAP收信件数
		 public static int imapnum=0;
		 public static int imapfirst=0;
		 //存放imap邮箱中未读邮件的数目
		 public int imap_unread=0;
		public  string MD5(string encryptString)
        {
            byte[] result = Encoding.Default.GetBytes(encryptString);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            string encryptResult = BitConverter.ToString(output).Replace("-", "");
            return encryptResult;
        }
		//下载邮件函数
		private void m_pImap_Fetch_MessageItems_UntaggedResponse(object sender,EventArgs<IMAP_r_u> e)
		{
          try{
                if(e.Value is IMAP_r_u_Fetch){
                IMAP_r_u_Fetch fetchResp = (IMAP_r_u_Fetch)e.Value;

                this.BeginInvoke(new MethodInvoker(delegate(){
                try
                {
					fetchResp.Rfc822.Stream.Position = 0;
                    Mail_Message mime = Mail_Message.ParseFromStream(fetchResp.Rfc822.Stream);
                    fetchResp.Rfc822.Stream.Dispose();  
                    
					//如果不超出时间范围则
					if(string.Compare(imap_end,imap_start)<=0 || (string.Compare(mime.Date.ToString("yyyy年MM月dd日 HH时mm分"),imap_start)>0 && string.Compare(mime.Date.ToString("yyyy年MM月dd日 HH时mm分"),imap_end)<0))
					{
						string from = "";
		            	if(fetchResp.Envelope.From != null)
		            	{
					    	for(int i=0;i<fetchResp.Envelope.From.Length;i++)
					    	{
								// Don't add ; for last item
								if(i == fetchResp.Envelope.From.Length - 1)
								{
									from += fetchResp.Envelope.From[i].ToString();
								}
								else
								{
									from += fetchResp.Envelope.From[i].ToString() + ";";
								}
							}
				        }
                        else
                        {
                        	from = "<none>";
                        }
                          
                        //写入文件
                        //截取邮件标题
						str stringhandle=new str();
						string title=from.ToString()+"#"+stringhandle.strlen(fetchResp.Envelope.Subject.ToString(),20)+"#"+fetchResp.InternalDate.Date.ToString("yyyy年MM月dd日 HH时mm分")+"#"+(fetchResp.Rfc822Size.Size / (decimal)1000).ToString("f2") + " kb#";
                        title=FilterSpecial(title);
                        cstring mystring=new cstring();
                        title=mystring.ENCODE(title);
						title+=".eml";	
						//写入eml文件
                        string filepro=Application.StartupPath+"\\data\\"+thisuser+"\\"+global_user+"\\"+folder+"\\"+title;
                        
                        //如果文件不存在,则下载,并且显示到控件中
                        if(!File.Exists(@filepro))
                       {
                        
							try
							{
								FileStream fs = new FileStream(filepro, FileMode.Create);//文件名和路径
				                StreamWriter sw = new StreamWriter(fs);
							    //开始写入
							    sw.Write(mime);					        
							    //清空缓冲区
							    sw.Flush();
							    //关闭流
							    sw.Close();
							    fs.Close();			
							}
							catch(Exception x)
							{
								//写入日志
						   		this.listBoxOUTPUT.Items.Add(log("all",thisuser,"eml文件",x.Message));
							}
                        			
							//列表显示							    
							if(global_type==1)
                            {
	                            ListViewItem currentItem = new ListViewItem();
	                            currentItem.ImageIndex = 0;
	                            currentItem.Tag = fetchResp.UID.UID;
	                            currentItem.Text = from;
	                            //截取邮件标题
								str stringhandle1=new str();
								currentItem.SubItems.Add(stringhandle1.strlen(fetchResp.Envelope.Subject != null ? fetchResp.Envelope.Subject : "<none>",20));
	                            currentItem.SubItems.Add(fetchResp.InternalDate.Date.ToString("yyyy.MM.dd HH:mm"));
	                            currentItem.SubItems.Add(((decimal)(fetchResp.Rfc822Size.Size / (decimal)1000)).ToString("f2") + " kb");
	                            //添加到控件中
	                            this.listView.Items.Add(currentItem);
                           	 }						        
                       }
                        	//MessageBox.Show("12");
					}
				}
                        catch(Exception x){
                           //写入日志
						   this.listBoxOUTPUT.Items.Add(log("all",thisuser,"eml文件",x.Message));
                        }
                    }));                    
                }
            }
            catch(Exception x){
                //写入日志
				this.listBoxOUTPUT.Items.Add(log("all",thisuser,"连接IMAP出错",x.Message));
            }   
            
        }
		//yahoo专用
		//下载邮件函数
		private void m_pImap_Fetch_MessageItems_UntaggedResponseyahoo(object sender,EventArgs<IMAP_r_u> e)
		{
          try{
                if(e.Value is IMAP_r_u_Fetch){
                IMAP_r_u_Fetch fetchResp = (IMAP_r_u_Fetch)e.Value;

                this.BeginInvoke(new MethodInvoker(delegate(){
                try
                {
                    
					//如果不超出时间范围则
					if(string.Compare(imap_end,imap_start)<=0 || (string.Compare(fetchResp.InternalDate.Date.ToString("yyyy年MM月dd日 HH时mm分"),imap_start)>0 && string.Compare(fetchResp.InternalDate.Date.ToString("yyyy年MM月dd日 HH时mm分"),imap_end)<0))
					{
						string from = "";
		            	if(fetchResp.Envelope.From != null)
		            	{
					    	for(int i=0;i<fetchResp.Envelope.From.Length;i++)
					    	{
								// Don't add ; for last item
								if(i == fetchResp.Envelope.From.Length - 1)
								{
									from += fetchResp.Envelope.From[i].ToString();
								}
								else
								{
									from += fetchResp.Envelope.From[i].ToString() + ";";
								}
							}
				        }
                        else
                        {
                        	from = "<none>";
                        }

                        			
							//列表显示							    
							if(global_type==1)
                            {
	                            ListViewItem currentItem = new ListViewItem();
	                            currentItem.ImageIndex = 0;
	                            currentItem.Tag = fetchResp.UID.UID;
	                            currentItem.Text = from;
	                            //截取邮件标题
								str stringhandle1=new str();
								currentItem.SubItems.Add(stringhandle1.strlen(fetchResp.Envelope.Subject != null ? fetchResp.Envelope.Subject : "<none>",20));
	                            currentItem.SubItems.Add(fetchResp.InternalDate.Date.ToString("yyyy.MM.dd HH:mm"));
	                            currentItem.SubItems.Add(((decimal)(fetchResp.Rfc822Size.Size / (decimal)1000)).ToString("f2") + " kb");
	                            //添加到控件中
	                            this.listView.Items.Add(currentItem);
                           	 }						        
                       
                        	//MessageBox.Show("12");
					}
				}
                        catch(Exception x){
                           //写入日志
						   this.listBoxOUTPUT.Items.Add(log("all",thisuser,"eml文件",x.Message));
                        }
                    }));                    
                }
            }
            catch(Exception x){
                //写入日志
				this.listBoxOUTPUT.Items.Add(log("all",thisuser,"连接IMAP出错",x.Message));
            }   
            
        }
		//IMAP邮件接收函数
		public void ReceiveIMAP(string serverport,string SSL,string PRO,string POP3Server,string UserName,string PassWord,string start,string end,int type,string first,string boxname)
		{
			//设置是否显示到列表中
			global_type=type;
			//开始建立
			try
			{
				//写入日志
				this.listBoxOUTPUT.Items.Add(log("imap",thisuser,"开始连接IMAP服务器 "+UserName,"OK"));
				IMAP_Client imap = new IMAP_Client();
				imap.Logger = new Logger();
				imap.Connect(POP3Server,int.Parse(serverport),(Convert.ToBoolean(string.Compare(SSL,"SSL")==0)));
				imap.Login(UserName,PassWord);
				//写入日志
				this.listBoxOUTPUT.Items.Add(log("imap",thisuser,"连接IMAP服务器成功"+UserName,"OK"));
				folder=boxname;					
				m_pImap=imap;
									
				listView.Items.Clear();
				this.Cursor = Cursors.WaitCursor;
			
				m_pImap.SelectFolder(boxname);
				string total="";
				if(int.Parse(first)>0)
				{
					total="1:"+first;
				}
				else
				{
					total="1:*";
				}
				//开始循环取邮件数据                
				m_pImap.Fetch(
				              false,
				              IMAP_t_SeqSet.Parse(total),
				              new IMAP_t_Fetch_i[]{
				              new IMAP_t_Fetch_i_Envelope(),
				              new IMAP_t_Fetch_i_Flags(),
				              new IMAP_t_Fetch_i_InternalDate(),
				              new IMAP_t_Fetch_i_Rfc822Size(),
				              new IMAP_t_Fetch_i_Uid(),
				              new IMAP_t_Fetch_i_Rfc822()
				              },
				              this.m_pImap_Fetch_MessageItems_UntaggedResponse
				                );
		    }
		    catch(Exception x)
			{
				//写入日志
				this.listBoxOUTPUT.Items.Add(log("imap",thisuser,"连接IMAP出错",x.Message));
			}
		}
		//POP3邮件接收函数
		public void ReceiveMail(string serverport,string SSL,string PRO,string POP3Server,string UserName,string PassWord,string start,string end,int type,string first)
		{
			//进程开始
			threadstate=1;
			//写入日志
			this.listBoxOUTPUT.Items.Add(log("pop3",thisuser,"开始连接POP3服务器 "+UserName,"OK"));
			//定义一个pop3客户端
				POP3_Client _POP3Client=new POP3_Client();
				Mail_Message mime;
				Mail_Message mime1;
				bool is_ssl;
			  	//定义存放每个邮箱中邮件uid的文件名
				string uidstorage="data\\"+thisuser+"\\"+UserName+"\\"+UserName+".log";
				//保存未读邮件数
				int couter=0;
				//保存已读取的邮件数
				int read_count=0;
				int READ=int.Parse(first);
				try
				{
					int int_serverport = 0;
	                int.TryParse(serverport, out int_serverport);
					if(SSL=="SSL")
						is_ssl=true;
					else
						is_ssl=false;
					//连接客户端服务器以及验证客户身份
					_POP3Client.Connect(POP3Server,int_serverport,is_ssl);
					_POP3Client.Authenticate(UserName,PassWord,true);
					this.listBoxOUTPUT.Items.Add(log("pop3",thisuser,"POP3服务器验证成功","OK"));
					//创建或打开存放邮件uid的文件
					FileStream fs1=new FileStream(uidstorage, FileMode.OpenOrCreate);
	                fs1.Close();
	                //定义一个读文件指针
				    FileStream file3= new FileStream(uidstorage, FileMode.Open);
				    StreamReader sr=new StreamReader(file3);
				    file3.Close();
	                sr.Close();
				    sr.Dispose();
				    var q=(from POP3_ClientMessage x in _POP3Client.Messages select x).OrderBy(x=>-x.SequenceNumber);  
				     string strLine;
				     foreach(POP3_ClientMessage message in  q) 
				     {
				        file3= new FileStream(uidstorage, FileMode.Open);
	                    sr=new StreamReader(file3);
				     	string ss = message.UID;
				     	//检查邮件的uid是否已经保存在对应邮箱的uid文件中
	                    strLine=sr.ReadLine();
	                    while(strLine!=null)
	                    {	 
	                    	if(strLine==ss)
	                    		break;
	                    	strLine=sr.ReadLine();
	                    }
	                    file3.Close();
	                    sr.Close();
				    	sr.Dispose();
	                    //uid不在文件中,则未读邮件数加一
	                    if(strLine==null)
	                    {
	                        StreamWriter sw1=new StreamWriter(uidstorage,true);
	                        try
	                        {
				              //提取每封邮件的头部并输出“邮件主题,发送者,发送时间以及邮件的大小”
				              mime=Mail_Message.ParseFromByte(message.HeaderToByte());
				    		 //满足时间条件就下载邮件
				    		if(string.Compare(end,start)<=0 || (string.Compare(mime.Date.ToString("yyyy年MM月dd日 HH时mm分"),start)>0 && string.Compare(mime.Date.ToString("yyyy年MM月dd日 HH时mm分"),end)<0))
				    		{
				    			if(type==1)
				    			{
				    				//定义一个列表
									ListViewItem currentItem = new ListViewItem();
	            					currentItem.ImageIndex = 0;
				    				currentItem.Text = mime.From.ToString();
				    				//截取邮件标题
									str stringhandle=new str();
									currentItem.SubItems.Add(stringhandle.strlen(mime.Subject.ToString(),20));
					    			currentItem.SubItems.Add(mime.Date.ToString("yyyy年MM月dd日 HH时mm分"));
					    			currentItem.SubItems.Add((message.Size/1024).ToString()+"KB");
					    			//添加到控件中
		                			listView.Items.Add(currentItem);
				    			}
	
				            	//将未读邮件的uid存放到对应的文件中
				    	        read_count++;
				    	        sw1.WriteLine(ss);
				                sw1.Close();
		                		//写入eml文件
		                		Random ran=new Random(unchecked((int)DateTime.Now.Ticks));		
								int RandKey=ran.Next(0,1000000000);
								
								//截取邮件标题
								str stringhandle2=new str();
								string title=mime.From.ToString()+"#"+stringhandle2.strlen(mime.Subject.ToString(),20)+"#"+mime.Date.ToString("yyyy年MM月dd日 HH时mm分")+"#"+(message.Size/1024).ToString()+"KB#";
	                            title=FilterSpecial(title);
	                            //对文件名进行BASE64加密
	                        	cstring mystring=new cstring();
                        		title=mystring.ENCODE(title);
								title+=".eml";	 
								string file=Application.StartupPath+"\\data\\"+thisuser+"\\"+UserName+"\\收件箱\\"+title;
		                		
								//写入eml文件
								FileStream fs = new FileStream(file, FileMode.Create);//文件名和路径
			                    StreamWriter sw = new StreamWriter(fs);
						        sw.Write(mime);
						        sw.Flush();
						        sw.Close();
						        fs.Close();
						        
						        mime1=Mail_Message.ParseFromByte(message.MessageToByte());
						        if(mime1.Attachments.Length!=0)
						        	Directory.CreateDirectory(Application.StartupPath+"\\data\\"+thisuser+"\\"+UserName+"\\收件箱\\"+RandKey.ToString()+".eml附件");
				    		  //下载邮件的每一个附件
						        for(int i=0;i<mime1.Attachments.Length;i++)
						        {
						        	Stream decodedDataStream = ((MIME_b_SinglepartBase)mime1.Attachments[i].Body).GetDataStream();
	                                string file1 =Application.StartupPath+"\\data\\"+thisuser+"\\"+UserName+"\\收件箱\\"+RandKey.ToString()+".eml附件"+"\\"+ mime1.Attachments[i].ContentType.Param_Name;
	                                using (FileStream fs2 = File.Create(file1))
	                                {
	                                	LumiSoft.Net.Net_Utils.StreamCopy(decodedDataStream, fs2, 4000);
	                                }
						        }
						        
				    		}
	                        }
	                        catch
	                        {
	                        	continue;
				            }  	
	                    }//if
	                    if(read_count==READ)
				   			break;
				     }//foreach
				     _POP3Client.Disconnect();
				}//try
				catch(Exception x)
				{
					//无法连接,加入到失败栏目
					string sql = "UPDATE profile SET STATE='0' WHERE USERNAME='"+UserName+"' AND PRO='"+PRO+"'";
					//插入到数据库
					SQLquery(sql);
					//添加到错误列表
					if(this.treeView.SelectedNode.Parent==null)
	                this.treeView.SelectedNode.ForeColor=Color.Red;
					else
					this.treeView.SelectedNode.Parent.ForeColor=Color.Red;						
					//写入日志
					this.listBoxOUTPUT.Items.Add(log("pop3",thisuser,"连接POP3服务器出错 "+UserName,x.Message));
				}
			//进程结束
			threadstate=0;
		}   
		

        private void m_pImap_Fetch_MessageItems_UntaggedResponse_1(object sender,EventArgs<IMAP_r_u> e)
        {
            /* NOTE: All IMAP untagged responses may be raised from thread pool thread,
                so all UI operations must use Invoke.
             
               There may be other untagged responses than FETCH, because IMAP server
               may send any untagged response to any command.
            */

            try{
                if(e.Value is IMAP_r_u_Fetch){
                    IMAP_r_u_Fetch fetchResp = (IMAP_r_u_Fetch)e.Value;

                    this.BeginInvoke(new MethodInvoker(delegate(){
                        try{
                            //ListViewItem currentItem = new ListViewItem();
                           // currentItem.ImageIndex = 0;
                           // currentItem.Tag = fetchResp.UID.UID;
							//fetchResp.Rfc822.Stream.Position = 0;
                           // Mail_Message mime = Mail_Message.ParseFromStream(fetchResp.Rfc822.Stream);
                           // fetchResp.Rfc822.Stream.Dispose();  
                            string from = "";
		                    if(fetchResp.Envelope.From != null){
				                for(int i=0;i<fetchResp.Envelope.From.Length;i++){
						            // Don't add ; for last item
						            if(i == fetchResp.Envelope.From.Length - 1){
							            from += fetchResp.Envelope.From[i].ToString();
						            }
						            else{
							            from += fetchResp.Envelope.From[i].ToString() + ";";
						            }
					            }
				            }
                            else{
                                from = "<none>";
                            }
                           // currentItem.Text = from;
                           //MessageBox.Show(from);

                           // currentItem.SubItems.Add(fetchResp.Envelope.Subject != null ? fetchResp.Envelope.Subject : "<none>");

                            //currentItem.SubItems.Add(fetchResp.InternalDate.Date.ToString("dd.MM.yyyy HH:mm"));

                           // currentItem.SubItems.Add(((decimal)(fetchResp.Rfc822Size.Size / (decimal)1000)).ToString("f2") + " kb");

                          //  m_pTabPageMail_Messages.Items.Add(currentItem);
                          	string title=from.ToString()+"#"+fetchResp.Envelope.Subject.ToString()+"#"+fetchResp.InternalDate.Date.ToString("yyyy年MM月dd日 HH时mm分")+"#"+(fetchResp.Rfc822Size.Size / (decimal)1000).ToString("f2") + " kb#";
                            title=FilterSpecial(title);
							title+=".eml";	
							//写入eml文件
                            string filepro=Application.StartupPath+"\\data\\"+global_user+"#IMAP\\INBOX\\"+title;
	                		FileStream fs = new FileStream(filepro, FileMode.Create);//文件名和路径
		                    StreamWriter sw = new StreamWriter(fs);
					        //开始写入
					        sw.Write("12");					        
					        //清空缓冲区
					        sw.Flush();
					        //关闭流
					        sw.Close();
					        fs.Close();
                        }
                        catch(Exception x){
                            MessageBox.Show("Error: " + x.ToString(),"Error:",MessageBoxButtons.OK,MessageBoxIcon.Error);
                        }
                    }));                    
                }
            }
            catch(Exception x){
                MessageBox.Show("Error: " + x.ToString(),"Error:",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }
		
		
		
		 void OnHookKeyDown(KeyEventArgs e)
        {
            OnKeyDown(e);
            if (e.Handled)
            {
                return;
            }
            
             if (((Control.ModifierKeys & Keys.Shift) == Keys.Shift) && ((Control.ModifierKeys & Keys.Control) == Keys.Control)
                     && ((Control.ModifierKeys & Keys.Alt) == Keys.Alt))
            {

                if (!this.Visible)
                {
                    this.Show();
                }
            }
            
            /*
            if (e.KeyCode == Keys.F10)
            {
                this.Hide();
            }
            */
        }
		
		
		
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			CheckForIllegalCrossThreadCalls = false;
			ActiveHook.SetWindowPos(this.Handle, IntPtr.Zero, 0, 0, 1000, 620, ActiveHook.SWP_NOACTIVATE);
            m_hook.OnKeyDown += new Hook.KeyboardDelegate(OnHookKeyDown);
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			
		}
		
		//数据库执行语句
		//插入数据库函数
		void SQLquery(string sql)
		{
			//打开数据库
			SQLiteConnection conn = new SQLiteConnection();
			SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
	        connstr.DataSource = "my.db";
	        conn.ConnectionString = connstr.ToString();
	        conn.Open();
	        //执行SQL语句    
	       	SQLiteCommand cmd = new SQLiteCommand();
	       	cmd.CommandText = sql;
	       	cmd.Connection = conn;
	       	cmd.ExecuteNonQuery();
	       	//关闭所有连接         
	       	connstr.Clear();
	       	conn.Close();
		}
				//加密解密算法
		public static string Encode(string str, string key)
		{
			DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
			provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
			provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
			byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(str);
			MemoryStream stream = new MemoryStream();
			CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
			stream2.Write(bytes, 0, bytes.Length);
			stream2.FlushFinalBlock();
			StringBuilder builder = new StringBuilder();
			foreach (byte num in stream.ToArray())
			{
			builder.AppendFormat("{0:X2}", num);
			}
			stream.Close();
			return builder.ToString();
		}
		public static string Decode(string str, string key)
		{
			DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
			provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
			provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
			byte[] buffer = new byte[str.Length / 2];
			for (int i = 0; i < (str.Length / 2); i++)
			{
			int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
			buffer[i] = (byte)num2;
			}
			MemoryStream stream = new MemoryStream();
			CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
			stream2.Write(buffer, 0, buffer.Length);
			stream2.FlushFinalBlock();
			stream.Close();
			return Encoding.GetEncoding("GB2312").GetString(stream.ToArray());
		}
		
		void TreeView1AfterSelect(object sender, TreeViewEventArgs e)
		{
			
		}
		
		//主窗体加载事件
		void MainFormLoad(object sender, EventArgs e)
		{
			 m_hook.SetHook(true); 
			//加载当前用户
			this.labelTHISUSER.Text=thisuser;
			//加载全局data目录
			if(!Directory.Exists("data"))Directory.CreateDirectory("data");
			//加载用户文件夹,如果存在则不创建,如果不存在则创建
			if(!Directory.Exists("data\\"+thisuser))Directory.CreateDirectory("data\\"+thisuser);
			//加载日志,如果存在则不创建,如果不存在则创建
			if(!Directory.Exists("log"))Directory.CreateDirectory("log");
			//如果不是admin用户 则隐藏用户管理选项
			if(thisuser!="admin")
			{
				this.用户添加ToolStripMenuItem.Visible=false;
			}
			
			
			/*加载定时器事件---------------------------------------*/
			int t=1000*60*15;
			try
			{
				string sql_config="select * from config where NAME='AUTO_TIME'";
				//打开数据库
				SQLiteConnection conn_config = new SQLiteConnection();
				SQLiteConnectionStringBuilder connstr_config = new SQLiteConnectionStringBuilder();
		        connstr_config.DataSource = "my.db";
		        conn_config.ConnectionString = connstr_config.ToString();
		        conn_config.Open();
		        //执行SQL语句    
		       	SQLiteCommand cmd_config = new SQLiteCommand();
		       	cmd_config.CommandText = sql_config;
		       	cmd_config.Connection = conn_config;
		       	SQLiteDataReader reader_config=cmd_config.ExecuteReader();
		       	
		       	while (reader_config.Read())
                {
		       		t=int.Parse(reader_config.GetString(2));
                }
		       	//关闭所有连接         
		       	connstr_config.Clear();
		       	conn_config.Close();
			}
			catch (Exception x)
			{
		        //写入日志
				this.listBoxOUTPUT.Items.Add(log("sqlite",thisuser,"定时器数据库连接出错 ",x.Message));
			}
			timerDOWNLOAD.Enabled=true;
			t=t<0?1000*60*15:1000*60*t;
			timerDOWNLOAD.Interval=t;
			/*加载定时器事件---------------------------------------*/
			//写入日志
			this.listBoxOUTPUT.Items.Add(log("sqlite",thisuser,"加载客户端软件","OK"));
			
			TaskTimer[] tt=new TaskTimer[10];
			treeView.Nodes.Clear();
			treeView.ImageList=imageListMAIL;
			
			//写入日志
			this.listBoxOUTPUT.Items.Add(log("sqlite",thisuser,"加载SQLITE数据库","OK"));
			
			try
			{
				SQLiteConnection conn = new SQLiteConnection();
				SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
	            connstr.DataSource = "my.db";
	            conn.ConnectionString = connstr.ToString();
	            conn.Open();	
			
	            //取得当前用户的所有文件夹,并且显示出来
	            string sql = "SELECT * FROM profile where UID='"+thisuser+"'";
	            SQLiteCommand cmd = new SQLiteCommand();
	            cmd.CommandText = sql;
	            cmd.Connection = conn;
	            SQLiteDataReader reader = cmd.ExecuteReader();
            
	            string username = "";
	            string password = "";
	            string serverip="";
	            string serverport="";
	            string serverssl="";
	            string pro="";
	            string time="";
	            string state="";
	            string nickname="";
	            while (reader.Read())
	                {
	                    username = reader.GetString(1);
	                    password = reader.GetString(2);
	                    serverip=reader.GetString(3);
	                    serverport=reader.GetString(4);
	                    serverssl=reader.GetString(5);
	                    pro=reader.GetString(6);
	                    time=reader.GetString(8);
	                    state=reader.GetString(11);
	                    nickname=reader.GetString(12);
	                    
	                    string dir;
	                    dir="data\\"+thisuser+"\\" +""+username;
	                    	
	                    TreeNode root = new TreeNode();
	                    if(string.Compare(nickname,"无")==0)
	                    {
	                    	root.Text=username;
	                    }
	                    else
	                    {
	                    	root.Text=username+"("+nickname+")";
	                    }
	                    	
	                    	
						if(pro=="IMAP")
						{
							root.ImageIndex=0;
							root.SelectedImageIndex=0;
						}
						else
						{
							root.ImageIndex=1;
							root.SelectedImageIndex=1;
						}
							
						if(Directory.Exists(dir))
						{
							DirectoryInfo[] list = new DirectoryInfo(@dir).GetDirectories();
							Array.Sort<DirectoryInfo>(list, new DirectoryLastTimeComparer());
							foreach(DirectoryInfo   d   in   list)//查找子目录     
							{  
								TreeNode son = new TreeNode();
								son.Text=d.ToString();
								son.SelectedImageIndex=2;
								son.ImageIndex=2;
								root.Nodes.Add(son);
							}
								
							//添加到树
							if(string.Compare(state,"0")==0)
							root.ForeColor=Color.Red;
								
							treeView.Nodes.Add(root);
						}
						else
						{
							
							Directory.CreateDirectory(dir);
							Directory.CreateDirectory(dir+"//收件箱");
							
							DirectoryInfo[] list = new DirectoryInfo(@dir).GetDirectories();
							Array.Sort<DirectoryInfo>(list, new DirectoryLastTimeComparer());
							foreach(DirectoryInfo   d   in   list)//查找子目录     
							{  
								TreeNode son = new TreeNode();
								son.Text=d.ToString();
								son.SelectedImageIndex=2;
								son.ImageIndex=2;
								root.Nodes.Add(son);
							}
								
							//添加到树
							if(string.Compare(state,"0")==0)
							root.ForeColor=Color.Red;
								
							treeView.Nodes.Add(root);
						}
						
					
						//写入日志
						this.listBoxOUTPUT.Items.Add(log("acount",thisuser,"加载账户"+username,"OK"));
						//有效邮箱++
						mail_able++;								 
	                }
	                connstr.Clear();
	                reader.Close();
	                conn.Close();
				}
				catch(Exception x)
				{
					//写入日志
					this.listBoxOUTPUT.Items.Add(log("sqlite\t",thisuser,"数据库加载错误  error:",x.Message));
					//删除出错账户
					//
					
				}
				
				//遍历所有文件夹
				DirectoryInfo folder = new DirectoryInfo(@Application.StartupPath+"\\");
  				GetAll(folder);

				this.labelGLOBAL.Text=this.labelGLOBAL.Text+" 总账户数:"+(mail_able+mail_unable).ToString();
				this.labelGLOBAL.Text=this.labelGLOBAL.Text+" 有效账户:"+mail_able.ToString()+" 无效账户:"+mail_unable.ToString();
				this.labelGLOBAL.Text=this.labelGLOBAL.Text+" 总邮件数:"+emlnum.ToString();
		}
		
		//左键点击事件
		void TreeViewNodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			treeView.SelectedNode=e.Node;
			if(e.Node.Parent!=null)
			{
				string[] title = this.treeView.SelectedNode.Parent.Text.Split(new char[] { '(' });
				//index=0 则代表是POP3
				string folder=title[0];
				//循环加载该目录中的所有文件
				  FileInfo[] fileInfo = new MyClass().GetFiles(@"data\\"+thisuser+"\\"+folder+"\\"+this.treeView.SelectedNode.Text);
				//清空列表
				listView.Items.Clear();
				int yishou=0;
		        foreach (FileInfo NextFile in fileInfo)  //遍历文件
		        {
		        	string str=NextFile.Name.ToString();
		        	str=str.Replace(".eml","");
		        	//BASE64解密
		        	cstring mystring=new cstring();
		        	string uncode=mystring.DECODE(str);
					string[] s = uncode.Split(new char[] { '#' });		
					try
					{
						yishou++;
						//定义一个列表
						ListViewItem currentItem = new ListViewItem();
	            		currentItem.ImageIndex = 0;
	            		currentItem.Text = s[0];
	            		currentItem.SubItems.Add(s[1]);
	            		currentItem.SubItems.Add(s[2]);
	            		currentItem.SubItems.Add(s[3]);
					    //添加到控件中
		                listView.Items.Add(currentItem);
					}
					catch(Exception x)
					{
						//写入日志
						this.listBoxOUTPUT.Items.Add(log("emlfile",thisuser,"加载已收文件格式出错 "+folder,x.Message));
					}
					
		       }//end foreach
		        this.labelSTATE.Text="新收0封";
		        this.labelYISHOU.Text="已收"+yishou.ToString()+"封";
			}
				
		}
			
		
		void 添加账户ToolStripMenuItemClick(object sender, EventArgs e)
		{
			FormSeting f=new FormSeting();
			f.thisuser=thisuser;
			if(f.ShowDialog()==DialogResult.OK)
			{
				//加载邮件文件夹目录
				string dir="data\\"+thisuser+"\\"+f.zhanghu;
				TreeNode root = new TreeNode();
				root.Text=f.zhanghu;
				if(f.xieyi=="IMAP")
				{
					root.ImageIndex=0;
					root.SelectedImageIndex=0;
				}
				else
				{
					root.ImageIndex=1;
					root.SelectedImageIndex=1;
				}
				
				DirectoryInfo   Dir=new   DirectoryInfo(dir);
				foreach(DirectoryInfo   d   in   Dir.GetDirectories())//查找子目录     
				{  
					TreeNode son = new TreeNode();
					son.Text=d.ToString();
					son.SelectedImageIndex=2;
					son.ImageIndex=2;
					root.Nodes.Add(son);
				}  
				treeView.Nodes.Add(root);
				
				//写入日志
				this.listBoxOUTPUT.Items.Add(log("add",thisuser,"增加账户成功"+f.zhanghu,"OK"));
			}
			
		}
		
		
		void 收邮件ToolStripMenuItemClick(object sender, EventArgs e)
		{	
			//空点击
			if(treeView.SelectedNode==null)return;
			//如果是子文件夹
			if(treeView.SelectedNode.Parent!=null)
			{
				if(treeView.SelectedNode.Parent.ForeColor==Color.Red)
				{
					return;
				}
			}
			//父节点
			if(treeView.SelectedNode.ForeColor==Color.Red)return;
			
			//执行收取邮件线程函数
			Thread oThread = new Thread(new ThreadStart(GET)); 
	  		oThread.Start();
			oThread.IsBackground=true;
			
			//写入日志
			this.listBoxOUTPUT.Items.Add(log("getmail",thisuser,"收取邮件","OK"));	
					
		}	
		//自定义函数
		public string GetMail()
		{
			return PREmail;
		}
		//自定义函数
		public string GetPro()
		{
			return PRPro;
		}
		//自定义函数
		public void Setthisuser(string str)
		{
			thisuser=str;
		}
		//自定义函数
		public string Getthisuser()
		{
			return thisuser;
		}
		void 自定义收件ToolStripMenuItemClick(object sender, EventArgs e)
		{
			if(treeView.SelectedNode!=null && treeView.SelectedNode.Parent==null && treeView.SelectedNode.ForeColor!=Color.Red)
			{
				string[] title = this.treeView.SelectedNode.Text.Split(new char[] { '(' });
				//POP3协议
				if(treeView.SelectedNode.ImageIndex==1 || (treeView.SelectedNode.Parent!=null && treeView.SelectedNode.Parent.ImageIndex==1))
				{
					PRPro="POP3";
				}
				else
				{
					PRPro="IMAP";
				}
				FormRULE f=new FormRULE();
				f.usr=title[0];
				f.pro=PRPro;
				if(f.ShowDialog()==DialogResult.OK)
				{
					
				}
			}
			
		}
		
		//右键收取邮件线程代理
		delegate void DEGET();
		//右键收取邮件线程函数
		public void GET()
		{
				
				//连接SQLite数据库
				SQLiteConnection conn = new SQLiteConnection();
				SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
	            connstr.DataSource = "my.db";
	            conn.ConnectionString = connstr.ToString();
	            conn.Open();

	            string usr ="";
		        string pass ="";
		        string ip="";
		        string port="";
		        string ssl="";
		        string pro="";
		        string start="";
		        string end="";
		        string tongbu="";
		        string first="-1";
	            //如果点击的是子节点且是POP3协议   imageIndex==1
	            if (treeView.SelectedNode.ImageIndex==1 || (treeView.SelectedNode.Parent!=null && treeView.SelectedNode.Parent.ImageIndex==1))
				{
					if(treeView.SelectedNode.ImageIndex==1)
					{
						string[] title = this.treeView.SelectedNode.Text.Split(new char[] { '(' });
						//取得当前点击的父节点名称  点击的是父节点的收取邮件
						usr=title[0];
					}
					else if(treeView.SelectedNode.Parent.ImageIndex==1)
					{
						string[] title = this.treeView.SelectedNode.Parent.Text.Split(new char[] { '(' });
						//若点击的是儿子节点,则取父亲的节点名称
						usr=title[0];
					}
					listView.Items.Clear();
					string sql = "SELECT * FROM profile WHERE USERNAME='"+usr+"'"; 
					SQLiteCommand cmd = new SQLiteCommand();
		           	cmd.CommandText = sql;
		            cmd.Connection = conn;
		            SQLiteDataReader reader = cmd.ExecuteReader();
		            //取出数据
		            while (reader.Read())
		            {
		                  	usr = reader.GetString(1);
		                    pass = reader.GetString(2);
		                    ip=reader.GetString(3);
		                    port=reader.GetString(4);
		                    ssl=reader.GetString(5);
		                    pro=reader.GetString(6);
		                    start=reader.GetString(7);
		                    end=reader.GetString(8);
		                    tongbu=reader.GetString(10);
		                    first=reader.GetString(14);
		            }
		            reader.Close();
		            this.Cursor = Cursors.WaitCursor;
		            this.labelTONGBU.Text="上次同步时间:"+tongbu;
		            //写入日志
					this.listBoxOUTPUT.Items.Add(log("pop3",thisuser,"开始收取POP3邮件 "+usr,"OK"));
					//判断用代理收取
					//在主函数中激活代理
					if(File.Exists("data\\"+thisuser+"\\"+usr+"\\server.txt"))
					{
						//打开读取
						string[] mapi;
						StreamReader sr = new StreamReader("data\\"+thisuser+"\\"+usr+"\\server.txt",Encoding.Default);
						string map=sr.ReadLine();
						sr.Close();
						mapi= map.Split(new char[] { ' ' });
						Random r=new Random();
						
						int localport=80+r.Next(0,1000);
						System.Diagnostics.Process.Start(@"proxy.exe",localport.ToString()+" "+mapi[0]+" "+mapi[1]+" "+ip+" "+port+" "+mapi[2]+" "+mapi[3]);
						ip="127.0.0.1";
						port=localport.ToString();
						ReceiveMail(port,ssl,pro,ip,usr,Decode(pass,"itbuluoge"),start,end,1,first);
					}
					else
					{
						ReceiveMail(port,ssl,pro,ip,usr,Decode(pass,"itbuluoge"),start,end,1,first);
					}
		            
		            this.labelSTATE.Text="新收"+this.listView.Items.Count.ToString()+"封";
		            this.Cursor = Cursors.Default;
		            //写入日志
					this.listBoxOUTPUT.Items.Add(log("pop3",thisuser,"收取POP3邮件完成 "+usr,"OK"));
		            
				}
				//如果点击的是子节点且是IMAP协议   imageIndex==0	
				else if(treeView.SelectedNode.ImageIndex==0 || treeView.SelectedNode.Parent.ImageIndex==0)
				{ 
					//线程存在
					threadstate=1;
					global_type=1;
					string boxname="";
					if(treeView.SelectedNode.ImageIndex==0)
					{
						//取得当前点击的父节点名称  点击的是父节点的收取邮件
	            		usr=treeView.SelectedNode.Text.ToString();
	            		boxname="INBOX";;
					}
					if(treeView.SelectedNode.Parent!=null && treeView.SelectedNode.Parent.ImageIndex==0)
					{
						//若点击的是儿子节点,则取父亲的节点名称
						usr=treeView.SelectedNode.Parent.Text.ToString();
						boxname=treeView.SelectedNode.Text.ToString();
					}
		            //到数据库中查询出该节点所属信息
		            string sql = "SELECT * FROM profile where USERNAME='"+usr+"'";           
		            SQLiteCommand cmd = new SQLiteCommand();
		            cmd.CommandText = sql;
		            cmd.Connection = conn;
		            SQLiteDataReader reader = cmd.ExecuteReader();
            
		            while (reader.Read())
		                {
		                    usr = reader.GetString(1);
		                    pass = reader.GetString(2);
		                    ip=reader.GetString(3);
		                    port=reader.GetString(4);
		                    ssl=reader.GetString(5);
		                    pro=reader.GetString(6);
		                    imap_start=reader.GetString(7);
		                    imap_end=reader.GetString(8);
		                    tongbu=reader.GetString(10);
		                    first=reader.GetString(14);
		                    imapfirst=int.Parse(first);
		                }
		            reader.Close();
		            this.labelTONGBU.Text="上次同步时间:"+tongbu;
		            try
		            {
		            	//在主函数中激活代理
						if(File.Exists("data\\"+thisuser+"\\"+usr+"\\server.txt"))
						{
							//打开读取
							string[] mapi;
							StreamReader sr = new StreamReader("data\\"+thisuser+"\\"+usr+"\\server.txt",Encoding.Default);
							string map=sr.ReadLine();
							sr.Close();
							mapi= map.Split(new char[] { ' ' });
							Random r=new Random();
							
							int localport=80+r.Next(0,1000);
							System.Diagnostics.Process.Start(@"proxy.exe",localport.ToString()+" "+mapi[0]+" "+mapi[1]+" "+ip+" "+port+" "+mapi[2]+" "+mapi[3]);
							ip="127.0.0.1";
							port=localport.ToString();
						}
				            //开始建立
							IMAP_Client imap = new IMAP_Client();
							imap.Logger = new Logger();
							imap.Connect(ip,int.Parse(port),(ssl=="SSL"));
							imap.Login(usr,Decode(pass,"itbuluoge"));
							global_user=usr;
							folder=boxname;					
							m_pImap=imap;
								
							listView.Items.Clear();
							 this.Cursor = Cursors.WaitCursor;
							try{
				                m_pImap.SelectFolder(boxname);
				                string total="";
				               if(imapfirst>0)
				               {
				                	total="1:"+imapfirst.ToString();
				                }
				                else
				                {
				                	total="1:*";
				                }
				                //如果是雅虎
				                if(ip=="apple.imap.mail.yahoo.com")
				                {
				                	//开始循环取邮件数据                
					                m_pImap.Fetch(
					                    true,
					                    IMAP_t_SeqSet.Parse("1:*"),
					                    new IMAP_t_Fetch_i[]{
					                      	new IMAP_t_Fetch_i_Envelope(),
					                        new IMAP_t_Fetch_i_Flags(),
					                        new IMAP_t_Fetch_i_InternalDate(),
					                        new IMAP_t_Fetch_i_Rfc822Size(),
					                        new IMAP_t_Fetch_i_Uid(),
					                        //new IMAP_t_Fetch_i_Rfc822()
					                    },
					                    this.m_pImap_Fetch_MessageItems_UntaggedResponseyahoo
					                );
				                	
				                	//写入邮件处
				                	if (listView.Items.Count > 0)
            						{
				                		for (int i=0;i<listView.Items.Count;i++)
											{
				                				LoadMessage((long)listView.Items[i].Tag);
											}

            						}
				                	//
				                }
				                else
				                {
				                	//开始循环取邮件数据                
					                m_pImap.Fetch(
					                    true,
					                    IMAP_t_SeqSet.Parse("1:*"),
					                    new IMAP_t_Fetch_i[]{
					                      	new IMAP_t_Fetch_i_Envelope(),
					                        new IMAP_t_Fetch_i_Flags(),
					                        new IMAP_t_Fetch_i_InternalDate(),
					                        new IMAP_t_Fetch_i_Rfc822Size(),
					                        new IMAP_t_Fetch_i_Uid(),
					                        new IMAP_t_Fetch_i_Rfc822()
					                    },
					                    this.m_pImap_Fetch_MessageItems_UntaggedResponse
					                );
				                }
								
				            }
				            catch(Exception x)
				            {
								//MessageBox.Show(x.ToString());
				               // MessageBox.Show(this,"Error: " + x.Message,"Error:",MessageBoxButtons.OK,MessageBoxIcon.Error);
				            }
							this.Cursor = Cursors.Default;
		            }
		            catch(Exception x)
				         {
							//写入日志
							//无法连接,加入到失败栏目
							string sql_w = "UPDATE profile SET STATE='0' WHERE USERNAME='"+usr+"'";
							//插入到数据库
							SQLquery(sql_w);
							//添加到错误列表
							if(this.treeView.SelectedNode.Parent==null)
			                this.treeView.SelectedNode.ForeColor=Color.Red;
							else
							this.treeView.SelectedNode.Parent.ForeColor=Color.Red;						
							//写入日志
							this.listBoxOUTPUT.Items.Add(log("imap\t",thisuser,"连接IMAP出错",x.Message));
				        }
		           
				}
				//线程结束
				threadstate=0;
				this.labelSTATE.Text="新收"+this.listView.Items.Count.ToString()+"封";
				conn.Close();
				//更改本次同步时间
		        string nowtime=System.DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分");
		        string sql1="update profile set TIME='"+nowtime+"' where USERNAME='"+usr+"'";
		        conn.Open();
		        SQLiteCommand cmd1 = new SQLiteCommand();
		        cmd1.CommandText = sql1;
		        cmd1.Connection = conn;
		        cmd1.ExecuteNonQuery();;
		        conn.Close();
		        
		        CloseProcess("test.exe");
		}
		//调用读取邮件函数
		private void LoadMessage(long uid)
        {     
            this.Cursor = Cursors.WaitCursor;
            try{
                // Start fetching.
                m_pImap.Fetch(
                    true,
                    IMAP_t_SeqSet.Parse(uid.ToString()),
                    new IMAP_t_Fetch_i[]{
                        new IMAP_t_Fetch_i_Rfc822()
                    },
                    this.m_pImap_Fetch_Message_UntaggedResponse
                );
            }
            catch(Exception x){
                MessageBox.Show(this,"Error: " + x.ToString(),"Error:",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            this.Cursor = Cursors.Default;
        }
		//邮件读取回调函数
		 private void m_pImap_Fetch_Message_UntaggedResponse(object sender,EventArgs<IMAP_r_u> e)
        {
            /* NOTE: All IMAP untagged responses may be raised from thread pool thread,
                so all UI operations must use Invoke.
             
               There may be other untagged responses than FETCH, because IMAP server
               may send any untagged response to any command.
            */

            try{
                if(e.Value is IMAP_r_u_Fetch){
                    IMAP_r_u_Fetch fetchResp = (IMAP_r_u_Fetch)e.Value;
                
                    this.BeginInvoke(new MethodInvoker(delegate(){
                        try{
                            fetchResp.Rfc822.Stream.Position = 0;
                            Mail_Message mime = Mail_Message.ParseFromStream(fetchResp.Rfc822.Stream);
                            fetchResp.Rfc822.Stream.Dispose();

                            //m_pTabPageMail_MessagesToolbar.Items["save"].Enabled = true;
                            //m_pTabPageMail_MessagesToolbar.Items["delete"].Enabled = true;
                                    
                            //m_pTabPageMail_MessageAttachments.Tag = mime;
                            foreach(MIME_Entity entity in mime.Attachments){
                                //ListViewItem item = new ListViewItem();
                                if(entity.ContentDisposition != null && entity.ContentDisposition.Param_FileName != null){
                                    //item.Text = entity.ContentDisposition.Param_FileName;
                                }
                                else{
                                   // item.Text = "untitled";
                                }
                                //item.ImageIndex = 0;
                               // item.Tag = entity;
                                //m_pTabPageMail_MessageAttachments.Items.Add(item);
                            }

                            if(mime.BodyText != null){
                               // m_pTabPageMail_MessageText.Text = mime.BodyText;
                            }
                            
                            try
                            {
                            	//写入eml
	                            str stringhandle=new str();
								string title=mime.From.ToString()+"#"+stringhandle.strlen(mime.Subject.ToString(),20)+"#"+mime.Date.ToString("yyyy年MM月dd日 HH时mm分")+"#"+(mime.BodyText.Length / (decimal)1000).ToString("f2") + " kb#";
		                        title=FilterSpecial(title);
		                        cstring mystring=new cstring();
		                        title=mystring.ENCODE(title);
								title+=".eml";	
								//写入eml文件
	                        	string filepro=Application.StartupPath+"\\data\\"+thisuser+"\\"+global_user+"\\"+folder+"\\"+title;
	                            FileStream fs = new FileStream(filepro, FileMode.Create);//文件名和路径
			                    StreamWriter sw = new StreamWriter(fs);
						        //开始写入
						        sw.Write(mime);					        
						        //清空缓冲区
						        sw.Flush();
						        //关闭流
						        sw.Close();
						        fs.Close();
                            }
                            catch(Exception x)
                            {
                            	
                            }
                            
                        }
                        catch(Exception x){
                            MessageBox.Show("Error: " + x.ToString(),"Error:",MessageBoxButtons.OK,MessageBoxIcon.Error);
                        }
                    }));
                }
            }
            catch(Exception x){
                MessageBox.Show("Error: " + x.ToString(),"Error:",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }
		//定时器事件
		public void theout(object source, EventArgs e) 
		{
			TaskTimer ttt = (TaskTimer)source;
			//MessageBox.Show(zhanghu[ttt.ID].usr+" "+zhanghu[ttt.ID].time.ToString());
			//在这里执行自动收信时间
//			if(zhanghu[ttt.ID].pro=="POP3")
//			{
//				ReceiveMail(zhanghu[ttt.ID].port.ToString(),zhanghu[ttt.ID].ssl,zhanghu[ttt.ID].pro,zhanghu[ttt.ID].ip,zhanghu[ttt.ID].usr,zhanghu[ttt.ID].pass);
//			}
			
		}
		
		//自动下载邮件事件
		void TimerDOWNLOADTick(object sender, EventArgs e)
		{
			/*
			//执行收取邮件线程函数
			Thread oThread = new Thread(new ThreadStart(AUTO)); 
  			oThread.Start();
			oThread.IsBackground=true;
			*/  
		}
		//全部收件
		public void ALL()
		{
			//进程开始
			threadstate=1;
			//写入日志
			this.listBoxOUTPUT.Items.Add(log("all",thisuser,"开始全部收信","OK"));
			//鼠标进入等待
			this.Cursor = Cursors.WaitCursor;
			try
			{
				SQLiteConnection conn = new SQLiteConnection();
				SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
		        connstr.DataSource = "my.db";
		        conn.ConnectionString = connstr.ToString();
		        conn.Open();
		        string sql = "SELECT * FROM profile where UID='"+thisuser+"' AND state='1'";
		        SQLiteCommand cmd = new SQLiteCommand();
		    	cmd.CommandText = sql;
		    	cmd.Connection = conn;
		    	SQLiteDataReader reader = cmd.ExecuteReader();
		    	
		    	//取出数据
			    string usr,pass,ip,port,ssl,pro,start,end,first="-1";
			    while (reader.Read())
		        {
			    	usr = reader.GetString(1);
		            pass = reader.GetString(2);
		            ip=reader.GetString(3);
		            port=reader.GetString(4);
		            ssl=reader.GetString(5);
		            pro=reader.GetString(6);
		            start=reader.GetString(7);
		            end=reader.GetString(8);
		            first=reader.GetString(14);
		            
		            global_user=usr;
		            //POP3处理下载邮件
		            if(string.Compare(pro,"POP3")==0)
		            {
						ReceiveMail(port,ssl,pro,ip,usr,Decode(pass,"itbuluoge"),start,end,0,first);
					}
		            else if(string.Compare(pro,"IMAP")==0)
		            {
		            	//ReceiveIMAP(port,ssl,pro,ip,usr,Decode(pass,"itbuluoge"),start,end,0,first,"INBOX");
						//开始建立
						try{
								IMAP_Client imap = new IMAP_Client();
								imap.Logger = new Logger();
								imap.Connect(ip,int.Parse(port),(ssl=="SSL"));
								imap.Login(usr,Decode(pass,"itbuluoge"));
								global_user=usr;
								global_type=0;
								folder="INBOX";					
								m_pImap=imap;
							
				                m_pImap.SelectFolder(folder);
				                string total="";
				                if(int.Parse(first)>0)
				                {
				                	total="1:"+first;
				                }
				                else
				                {
				                	total="1:*";
				                }
								//开始循环取邮件数据                
				                m_pImap.Fetch(
				                    false,
				                    IMAP_t_SeqSet.Parse(total),
				                    new IMAP_t_Fetch_i[]{
				                      	new IMAP_t_Fetch_i_Envelope(),
				                        new IMAP_t_Fetch_i_Flags(),
				                        new IMAP_t_Fetch_i_InternalDate(),
				                        new IMAP_t_Fetch_i_Rfc822Size(),
				                        new IMAP_t_Fetch_i_Uid(),
				                         new IMAP_t_Fetch_i_Rfc822()
				                    },
				                    this.m_pImap_Fetch_MessageItems_UntaggedResponse
				                );
				            }
							 catch(Exception x)
							 {
							 	//写入日志
								this.listBoxOUTPUT.Items.Add(log("all",thisuser,"连接IMAP出错",x.Message));
							 }
							 
							
		           
		            }
			    }
			    
			   
			}
			catch(Exception x)
			{
				//写入日志
				this.listBoxOUTPUT.Items.Add(log("all",thisuser,"数据库错误",x.Message));
			}
			 //写入日志
				this.listBoxOUTPUT.Items.Add(log("all",thisuser,"全部收信结束","OK"));

			//鼠标恢复
			this.Cursor = Cursors.Default;
			//进程结束
			threadstate=0;
		}
		//执行收取邮件线程函数
		public void AUTO()
		{
			//进程开始
			threadstate=1;
			//写入日志
			this.listBoxOUTPUT.Items.Add(log("auto",thisuser,"开始自动收信","OK"));
			//连接SQLite数据库
			SQLiteConnection conn = new SQLiteConnection();
			SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
	        connstr.DataSource = "my.db";
	        conn.ConnectionString = connstr.ToString();
	        conn.Open();
            
            this.Cursor = Cursors.WaitCursor;
            string sql = "SELECT * FROM profile"; 
			SQLiteCommand cmd = new SQLiteCommand();
		    cmd.CommandText = sql;
		    cmd.Connection = conn;
		    SQLiteDataReader reader = cmd.ExecuteReader();
		    
		    //取出数据
		    string usr ="";
		    string pass ="";
		    string ip="";
		    string port="";
		    string ssl="";
		    string pro="";
		    string start="";
		    string end="";
		    string each_auto="";
		    string first="-1";
		    while (reader.Read())
		          {
		                  	usr = reader.GetString(1);
		                    pass = reader.GetString(2);
		                    ip=reader.GetString(3);
		                    port=reader.GetString(4);
		                    ssl=reader.GetString(5);
		                    pro=reader.GetString(6);
		                    start=reader.GetString(7);
		                    end=reader.GetString(8);
		                    each_auto=reader.GetString(13);

		    				//POP3处理下载邮件
						    if(pro=="POP3" && string.Compare(each_auto,auto)==0)
						    {
						    	ReceiveMail(port,ssl,pro,ip,usr,Decode(pass,"itbuluoge"),start,end,0,first);
						    }
						    if(pro=="IMAP" && string.Compare(each_auto,auto)==0)
						    {
						    	global_type=0;
						    	//开始建立
								IMAP_Client imap = new IMAP_Client();
								imap.Logger = new Logger();
								imap.Connect(ip,int.Parse(port),(ssl=="SSL"));
								imap.Login(usr,Decode(pass,"itbuluoge"));
								global_user=usr;
								folder="INBOX";					
								m_pImap=imap;
						
								try{
		                			m_pImap.SelectFolder("INBOX");
		                
									//开始循环取邮件数据                
		                			m_pImap.Fetch(
							                    false,
							                    IMAP_t_SeqSet.Parse("1:*"),
							                    new IMAP_t_Fetch_i[]{
						                      	new IMAP_t_Fetch_i_Envelope(),
						                        new IMAP_t_Fetch_i_Flags(),
						                        new IMAP_t_Fetch_i_InternalDate(),
						                        new IMAP_t_Fetch_i_Rfc822Size(),
						                        new IMAP_t_Fetch_i_Uid(),
						                        new IMAP_t_Fetch_i_Rfc822()
		                    },
		                    this.m_pImap_Fetch_MessageItems_UntaggedResponse
		                );
		            }
		            catch(Exception x)
		            {
						//MessageBox.Show(x.ToString());
		               // MessageBox.Show(this,"Error: " + x.Message,"Error:",MessageBoxButtons.OK,MessageBoxIcon.Error);
		            }

					 }
		    
		         }
		            
		   this.Cursor = Cursors.Default;
		   //写入日志
			this.listBoxOUTPUT.Items.Add(log("automail\t",thisuser,"自动收信完成","OK"));
		   //进程结束
			threadstate=0;
            
		}		
		
		void 删除账户ToolStripMenuItemClick(object sender, EventArgs e)
		{
			
			if(treeView.SelectedNode!=null && treeView.SelectedNode.Parent==null)
			{
				if (MessageBox.Show("将删除所有邮件信息?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
			  	{
			  		//删除
			  		try
					{
						string[] title = this.treeView.SelectedNode.Text.Split(new char[] { '(' });
						SQLiteConnection conn = new SQLiteConnection();
						SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
				        connstr.DataSource = "my.db";
				        conn.ConnectionString = connstr.ToString();
				        conn.Open();
				        //执行SQL语句  
				        string user="";
						string name="";	        
						user=title[0];
				        if(treeView.SelectedNode.ImageIndex==1)
				         	name="POP3";
				        else
				         	name="IMAP";
						string sql = "DELETE  FROM profile where USERNAME='"+user+"' AND UID='"+thisuser+"'";   			
				       	SQLiteCommand cmd = new SQLiteCommand();
				       	cmd.CommandText = sql;
				       	cmd.Connection = conn;
				       	cmd.ExecuteNonQuery();
				       	treeView.Nodes.Remove(treeView.SelectedNode);
				       	//关闭所有连接         
				       	connstr.Clear();
				       	conn.Close();
	
				       	//删除目录
				       	System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"data\\"+thisuser+"\\"+user);
			            di.Delete(true);
			            
			            //写入日志
						this.listBoxOUTPUT.Items.Add(log("dele",thisuser,"删除账户成功"+user,"OK"));
			         
					}
					catch(Exception x)
					{
						//写入日志
						this.listBoxOUTPUT.Items.Add(log("dele",thisuser,"数据库删除错误 ",x.Message));
					}
			  	}
				
				
			}
			
	   }
			
		//文件名过滤函数
			public string FilterSpecial(string strHtml)
			{
				if(string.Empty == strHtml)
				{
					return strHtml;
				}
				string[] aryReg = {"\"", "'", "'delete", "?", "<", ">","%", "\"\"",
					",","_", ";",":","\\",
					"||", "[", "]", "&", "/", "-", 
					"=", " ", "、", ";", "。", "”", "“", 
					"|", " ", "''" ,"【","】"};
				for (int i = 0; i < aryReg.Length; i++)
				{
				     strHtml = strHtml.Replace(aryReg[i], string.Empty);
				}
     			return strHtml;
			}
		//返回当前日期函数
		public string log(string id,string usr,string action,string state)
		{
			//创建或打开系统日志
		    string systemlog=@"log\\system.log";
		    try
		    {
		    	FileStream fs=new FileStream(systemlog, FileMode.Append);
			    StreamWriter sw = new StreamWriter(fs,Encoding.GetEncoding("gb2312"));
				//开始写入
				sw.Write(id+"\t"+System.DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分")+" "+usr+"\t"+action+"\t\t\t\t"+state+"\r\n");
				//清空缓冲区
				sw.Flush();
				//关闭流
				sw.Close();
				fs.Close();
		    }
		    catch(Exception e)
		    {
		    	;
		    }
			
			return id+"\t"+System.DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分")+" "+usr+"\t"+action+"\t\t\t\t"+state;
		
		}
		//写入用户登陆
		public void write_userlog(string user,string action)
		{
			try
			{
				//创建或打开用户登陆日志
			    string userlog=@"log\\"+user+".log";
				FileStream fs=new FileStream(userlog, FileMode.Append);
			    StreamWriter sw = new StreamWriter(fs,Encoding.GetEncoding("gb2312"));
				//开始写入
				sw.Write(log("logon\t",user,action,"OK")+"\r\n");
				//清空缓冲区
				sw.Flush();
				//关闭流
				sw.Close();
				fs.Close();
			}
			catch(Exception e)
		    {
		    	;
		    }
			
			
			
		}
		
		void GetAll(DirectoryInfo dir)//搜索文件夹中的文件
        {
            FileInfo[] allFile = dir.GetFiles();
            foreach (FileInfo fi in allFile)
            {
            	if(fi.Name.Contains(".eml"))emlnum++;

            }

            DirectoryInfo[] allDir= dir.GetDirectories();
            foreach (DirectoryInfo d in allDir)
            {
                GetAll(d);
            }
        }
		
		void MainFormFormClosing(object sender, FormClosingEventArgs e)
		{
			//线程存在
			if(threadstate==1)
			{
				e.Cancel =true ;
	            this.WindowState = FormWindowState.Minimized;
	            this.Visible = false;
			}
			else
			{
				write_userlog(thisuser,"用户退出");
			}
			
			
		}
		private void notifyIcon_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                return;
            }   
        }
		private void toolStripMenuItemClose_Click(object sender, EventArgs e)
        {
           Environment.Exit(0);
        }
		
		void 打开ToolStripMenuItemClick(object sender, EventArgs e)
		{
			 this.Visible = true;
             this.WindowState = FormWindowState.Normal;
             return;
		}
		
		void 退出ToolStripMenuItemClick(object sender, EventArgs e)
		{
			  if (MessageBox.Show("您确定要退出邮件客户端吗?", "确认退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
			  	write_userlog(thisuser,"用户退出");
                this.notifyIconSMALL.Visible = false;
                this.Close();
                this.Dispose();
                Application.Exit();			
			}
		}
		
		void 同步设置ToolStripMenuItemClick(object sender, EventArgs e)
		{
			FormGLOBAL f=new FormGLOBAL();
			if(f.ShowDialog()==DialogResult.OK)
			{
				//MessageBox.Show("ok");
			}		
		}
		
		void 登陆日志ToolStripMenuItemClick(object sender, EventArgs e)
		{
			//System.Diagnostics.Process.Start(thisuser+".log");
			FormSHOWLOG f=new FormSHOWLOG();
			f.logfile="log\\"+thisuser+".log";
			f.Text="登陆日志";
			f.ShowDialog();
		}
		
		void 用户添加ToolStripMenuItemClick(object sender, EventArgs e)
		{
			FormUSER f=new FormUSER();
			if(f.ShowDialog()==DialogResult.OK)
			{
				//
			}	
		}
		
		void 账户属性ToolStripMenuItemClick(object sender, EventArgs e)
		{
			if(treeView.SelectedNode!=null && treeView.SelectedNode.Parent==null)
			{
				
				string[] title = this.treeView.SelectedNode.Text.Split(new char[] { '(' });
				PREmail=title[0];
				//POP3协议
				if(treeView.SelectedNode.ImageIndex==1 || (treeView.SelectedNode.Parent!=null && treeView.SelectedNode.Parent.ImageIndex==1))
				{
					PRPro="POP3";
				}
				else
				{
					PRPro="IMAP";
				}
				FormZHANGHU f=new FormZHANGHU();
				if(f.ShowDialog()==DialogResult.OK)
				{
					//更新状态
					treeView.SelectedNode.ForeColor=Color.Black;
					string sql = "UPDATE profile SET STATE='1' WHERE USERNAME='"+title[0]+"'";
					//插入到数据库
					SQLquery(sql);
				}	
			}
			
		}
		
		void 系统日志ToolStripMenuItemClick(object sender, EventArgs e)
		{
			FormSHOWLOG f=new FormSHOWLOG();
			f.logfile="log\\system.log";
			f.Text="系统日志";
			f.ShowDialog();			
		}
		
		void 添加代理ToolStripMenuItemClick(object sender, EventArgs e)
		{
			FormADDproxy f=new FormADDproxy();
			f.ShowDialog();	
			//MessageBox.Show("该功能在下个版本中支持!");
		}
		
		void 帮助ToolStripMenuItemClick(object sender, EventArgs e)
		{
			FormHELP f=new FormHELP();
			f.ShowDialog();		
		}
		
		void 代理设置ToolStripMenuItem1Click(object sender, EventArgs e)
		{
			if(treeView.SelectedNode!=null && treeView.SelectedNode.Parent==null && treeView.SelectedNode.ForeColor!=Color.Red)
			{
				string[] title = this.treeView.SelectedNode.Text.Split(new char[] { '(' });
				//POP3协议
				if(treeView.SelectedNode.ImageIndex==1 || (treeView.SelectedNode.Parent!=null && treeView.SelectedNode.Parent.ImageIndex==1))
				{
					PRPro="POP3";
				}
				else
				{
					PRPro="IMAP";
				}
				
				FormPROXY f=new FormPROXY();
				f.thisuser=thisuser;
				f.usr=title[0];
				f.pro=PRPro;
				f.ShowDialog();
				
			}
			
		}
		public void CloseProcess(string ProcessName)
        {
            Process[] p = Process.GetProcessesByName(ProcessName);
            if (p.Length > 0)
            {
                try
                {
                    p[0].Kill();
                }
                catch
                {
                    ;  
                }
            }
        }
		
		void 备注ToolStripMenuItemClick(object sender, EventArgs e)
		{
			if(treeView.SelectedNode!=null && treeView.SelectedNode.Parent==null)
			{
				string[] title = this.treeView.SelectedNode.Text.Split(new char[] { '(' });
				//POP3协议
				if(treeView.SelectedNode.ImageIndex==1 || (treeView.SelectedNode.Parent!=null && treeView.SelectedNode.Parent.ImageIndex==1))
				{
					PRPro="POP3";
				}
				else
				{
					PRPro="IMAP";
				}
				FormMEMO f=new FormMEMO();
				f.usr=title[0];
				f.pro=PRPro;
				if(f.ShowDialog()==DialogResult.OK)
				{
					
					if(string.Compare(f.memo,"")!=0)
					{
						this.treeView.SelectedNode.Text=title[0]+"(";
						this.treeView.SelectedNode.Text+=f.memo;
						this.treeView.SelectedNode.Text+=")";
					}
					else
					{
						this.treeView.SelectedNode.Text=title[0];
					}
					
				}	
			
			}
		}
		
		//15分钟自动收信
		void Timer15Tick(object sender, EventArgs e)
		{
			//执行收取邮件线程函数
			auto="15";
			Thread oThread = new Thread(new ThreadStart(AUTO)); 
  			oThread.Start();
			oThread.IsBackground=true;  			
		}
		//30分钟自动收信
		void Timer30Tick(object sender, EventArgs e)
		{
			//执行收取邮件线程函数
			auto="30";
			Thread oThread = new Thread(new ThreadStart(AUTO)); 
  			oThread.Start();
			oThread.IsBackground=true;  			
		}
		//60分钟自动收信
		void Timer60Tick(object sender, EventArgs e)
		{
			//执行收取邮件线程函数
			auto="60";
			Thread oThread = new Thread(new ThreadStart(AUTO)); 
  			oThread.Start();
			oThread.IsBackground=true;  		
		}
		
		Thread alloThread;
		void 全部收件ToolStripMenuItemClick(object sender, EventArgs e)
		{
			alloThread = new Thread(new ThreadStart(ALL)); 
  			alloThread.Start();
			alloThread.IsBackground=true; 	
		}
		
		void 全部停止ToolStripMenuItemClick(object sender, EventArgs e)
		{
			alloThread.Abort();
			this.Cursor = Cursors.Default;
		}
		
		void MainFormKeyDown(object sender, KeyEventArgs e)
		{
			   if (e.Alt && e.KeyCode == Keys.A)
            	{
			   		this.Hide();
            	}
		}
		
		void MainFormFormClosed(object sender, FormClosedEventArgs e)
		{
			 m_hook.SetHook(false);	
		}
		
		void 删除账户ToolStripMenuItem1Click(object sender, EventArgs e)
		{
			try
				{
					string[] title = this.treeView.SelectedNode.Text.Split(new char[] { '(' });
					SQLiteConnection conn = new SQLiteConnection();
					SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
			        connstr.DataSource = "my.db";
			        conn.ConnectionString = connstr.ToString();
			        conn.Open();
			        //执行SQL语句  
			        string user="";
					string name="";	        
					user=title[0];
			        if(treeView.SelectedNode.ImageIndex==1)
			         	name="POP3";
			        else
			         	name="IMAP";
					string sql = "DELETE  FROM profile where USERNAME='"+user+"'AND PRO='"+name+"'";   			
			       	SQLiteCommand cmd = new SQLiteCommand();
			       	cmd.CommandText = sql;
			       	cmd.Connection = conn;
			       	cmd.ExecuteNonQuery();
			       	treeView.Nodes.Remove(treeView.SelectedNode);
			       	//关闭所有连接         
			       	connstr.Clear();
			       	conn.Close();
			       	
			       	//删除目录
			       	System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@user+"#"+name);
		            di.Delete(true);
		            
		            //写入日志
					this.listBoxOUTPUT.Items.Add(log("dele",thisuser,"删除账户成功"+user,"OK"));
		         
				}
				catch(Exception x)
				{
					//写入日志
					this.listBoxOUTPUT.Items.Add(log("dele",thisuser,"数据库删除错误 ",x.Message));
				}			
		}
		
		void 代理管理ToolStripMenuItemClick(object sender, EventArgs e)
		{
			FormADMINproxy f=new FormADMINproxy();
			if(f.ShowDialog()==DialogResult.OK)
			{
				//
			}				
		}
	}
	
	public class TaskTimer : System.Windows.Forms.Timer
 {
  #region <变量>
  /// <summary>
  /// 定时器id
  /// </summary>
  private int id;
  /// <summary>
  /// 定时器参数
  /// </summary>
  private  string param ;
  public static int num;
  #endregion

  #region <属性>
  /// <summary>
  /// 定时器id属性
  /// </summary>
  public int ID
  {
   set{id = value;}
   get{return id;}
  }
  /// <summary>
  /// 定时器参数属性
  /// </summary>
  public string Param 
  {
   set{param = value;}
   get{return param;}
  }
  
  #endregion
  ///<summary>
  /// 构造函数
  /// </summary>
  public TaskTimer() : base ()
  {

  }
  
   
	}
	
	//LISTVIEW新类 防止闪动
	class ListViewNF : System.Windows.Forms.ListView
    {
        public ListViewNF()
        {
            // 开启双缓冲
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);

            // Enable the OnNotifyMessage event so we get a chance to filter out 
            // Windows messages before they get to the form's WndProc
            this.SetStyle(ControlStyles.EnableNotifyMessage, true);
        }

        protected override void OnNotifyMessage(Message m)
        {
            //Filter out the WM_ERASEBKGND message
            if (m.Msg != 0x14)
            {
                base.OnNotifyMessage(m);
            }

        }


    }
	
	//文件名排序类
	public class FileComparer : IComparer
        {
            int IComparer.Compare(Object o1, Object o2)
            {
                FileInfo fi1 = o1 as FileInfo;
                FileInfo fi2 = o2 as FileInfo;
                return fi1.CreationTime.CompareTo(fi2.CreationTime);
            }
        }
	
	//文件夹排名类
	//文件夹中按时间排序最新的文件读取
    public class DirectoryLastTimeComparer : IComparer<DirectoryInfo>
    {
        #region IComparer<DirectoryInfo> 成员

        public int Compare(DirectoryInfo x, DirectoryInfo y)
        {
            return x.LastWriteTime.CompareTo(y.LastWriteTime);

        }

        #endregion
    }

    //文件夹中按时间排序最新的文件读取
    public class FIleLastTimeComparer : IComparer<FileInfo>
    {
        #region IComparer<FileInfo> 成员

        public int Compare(FileInfo x, FileInfo y)
        {
            return y.LastWriteTime.CompareTo(x.LastWriteTime);
        }

        #endregion
    } 

        public class MyClass
        {
            public FileInfo[] GetFiles(string path)
            {
                DirectoryInfo di = new DirectoryInfo(path);
                FileInfo[] files = di.GetFiles();
                FileComparer fc = new FileComparer();
                Array.Sort(files, fc);
                return files;
            }
        } 
        
        class ActiveHook
    {
        /*****************************************
         * Created By: Jickie 阿文
         * Created: 2009/10/29
         * **************************************/

        public const int WM_KEYDOWN = 0x0100;
        public const int WM_KEYUP = 0x0101;
        public const int WM_CHAR = 0x0102;

        public const int SWP_NOSIZE = 0x0001;
        public const int SWP_NOMOVE = 0x0002;
        public const int SWP_NOZORDER = 0x0004;
        public const int SWP_NOREDRAW = 0x0008;
        public const int SWP_NOACTIVATE = 0x0010;
        public const int SWP_FRAMECHANGED = 0x0020;  /* The frame changed: send WM_NCCALCSIZE */
        public const int SWP_SHOWWINDOW = 0x0040;
        public const int SWP_HIDEWINDOW = 0x0080;
        public const int SWP_NOCOPYBITS = 0x0100;
        public const int SWP_NOOWNERZORDER = 0x0200;  /* Don't do owner Z ordering */
        public const int SWP_NOSENDCHANGING = 0x0400;  /* Don't send WM_WINDOWPOSCHANGING */

        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, int flags);

        public const uint WS_OVERLAPPED = WS_BORDER | WS_CAPTION;
        public const uint WS_CLIPSIBLINGS = 0x04000000;
        public const uint WS_CLIPCHILDREN = 0x02000000;
        public const uint WS_CAPTION = 0x00C00000;     /* WS_BORDER | WS_DLGFRAME  */
        public const uint WS_BORDER = 0x00800000;
        public const uint WS_DLGFRAME = 0x00400000;
        public const uint WS_VSCROLL = 0x00200000;
        public const uint WS_HSCROLL = 0x00100000;
        public const uint WS_SYSMENU = 0x00080000;
        public const uint WS_THICKFRAME = 0x00040000;
        public const uint WS_MAXIMIZEBOX = 0x00020000;
        public const uint WS_MINIMIZEBOX = 0x00010000;
        public const uint WS_SIZEBOX = WS_THICKFRAME;
        public const uint WS_POPUP = 0x80000000;
        public const uint WS_CHILD = 0x40000000;
        public const uint WS_VISIBLE = 0x10000000;
        public const uint WS_DISABLED = 0x08000000;

        public const uint WS_EX_DLGMODALFRAME = 0x00000001;
        public const uint WS_EX_TOPMOST = 0x00000008;
        public const uint WS_EX_TOOLWINDOW = 0x00000080;
        public const uint WS_EX_WINDOWEDGE = 0x00000100;
        public const uint WS_EX_CLIENTEDGE = 0x00000200;

        public const uint WS_EX_CONTEXTHELP = 0x00000400;
        public const uint WS_EX_STATICEDGE = 0x00020000;
        public const uint WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE);

        public const int GWL_STYLE = (-16);
        public const int GWL_EXSTYLE = (-20);

        [DllImport("user32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Auto)]
        public static extern IntPtr GetWindowLong32(IntPtr hWnd, int nIndex);

        [DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]
        public static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, int dwNewLong);

public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);

        public const int WH_KEYBOARD = 2;
        public const int WH_MOUSE = 7;
        public const int WH_KEYBOARD_LL = 13;
        public const int WH_MOUSE_LL = 14;

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);

        [StructLayout(LayoutKind.Sequential)]
        public class POINT
        {
            public int x;
            public int y;
        }

        [StructLayout(LayoutKind.Sequential)]
        public class MouseHookStruct
        {
            public POINT pt;
            public int hwnd;
            public int wHitTestCode;
            public int dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        public class KeyboardHookStruct
        {
            public int vkCode;
            public int scanCode;
            public int flags;
            public int time;
            public int dwExtraInfo;
        }
    }

public class Hook
    {
        public delegate void KeyboardDelegate(KeyEventArgs e);
        public KeyboardDelegate OnKeyDown;
        int m_hHook = 0;
        ActiveHook.HookProc m_HookCallback;

        public void SetHook(bool enable)
        {
            if (enable && m_hHook == 0)
            {
                m_HookCallback = new ActiveHook.HookProc(HookCallbackProc);
                Module module = Assembly.GetExecutingAssembly().GetModules()[0];
                m_hHook = ActiveHook.SetWindowsHookEx(ActiveHook.WH_KEYBOARD_LL, m_HookCallback, Marshal.GetHINSTANCE(module), 0);
                return;
            }

            if (enable == false && m_hHook != 0)
            {
                ActiveHook.UnhookWindowsHookEx(m_hHook);
                m_hHook = 0;
            }
        }
        int HookCallbackProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode < 0)
            {
                return ActiveHook.CallNextHookEx(m_hHook, nCode, wParam, lParam);
            }
            else
            {
                ActiveHook.KeyboardHookStruct hookstruct = (ActiveHook.KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(ActiveHook.KeyboardHookStruct));

                if (OnKeyDown != null && wParam.ToInt32() == ActiveHook.WM_KEYDOWN)
                {
                    Keys key = (Keys)hookstruct.vkCode;
                    if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
                        key |= Keys.Shift;
                    if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
                        key |= Keys.Control;
                     if ((Control.ModifierKeys & Keys.Alt) == Keys.Alt)
                         key |= Keys.Alt;

                    KeyEventArgs e = new KeyEventArgs(key);
                    e.Handled = false;
                    OnKeyDown(e);
                    if (e.Handled)
                        return 1;
                }
                int result = 0;
                if (m_hHook != 0)
                    result = ActiveHook.CallNextHookEx(m_hHook, nCode, wParam, lParam);
                return result;
            }
        }
    }
}

代码有点多,但是是核心代码。可以作为参考。


工程采用SHARPDEVELOP开发,32位操作系统检验通过。

需要详细资料可以登录到IT部落格

IT部落格(http://www.itbuluoge.com)-快乐快速学习,专注于免费编程教程,在线编程,IT面试笔记,IT面试经验

C#邮件接收系统核心代码(接收POP3邮件IMAP邮件),布布扣,bubuko.com

C#邮件接收系统核心代码(接收POP3邮件IMAP邮件)

标签:des   c   style   class   blog   code   

原文地址:http://blog.csdn.net/itbuluoge/article/details/29802339

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!