namespace FileStreamRead { class Program { static void Main(string[] args) { FileStream fs; //得到文件所在路径 string filePath = "C:\\file1.txt"; //打开文件 try { fs = new FileStream(filePath, FileMode.Open); } catch(Exception) { throw; } //还没有读取的文件内容长度 long left = fs.Length; //存储读取结果 byte[] bytes = new byte[100]; //每次读取长度 int maxLength = bytes.Length; //读取位置 int start = 0; //实际返回结果长度 int num = 0; //当文件未读取长度大于0时,不断进行读取 while (left > 0) { fs.Position = start; num = 0; if (left < maxLength) num = fs.Read(bytes, 0, Convert.ToInt32(left)); else num = fs.Read(bytes, 0, maxLength); if (num == 0) break; start += num; left -= num; Console.WriteLine(Encoding.UTF8.GetString(bytes)); } Console.WriteLine("end of file"); Console.ReadLine(); fs.Close(); } } }
C#文件列表操做四大重点javascript
C#文件列表要点1:上传文件 HTML部分: 1. 〈 formid=\"form1\"runat=\" 2. server\"method=\"post\"enctype=\ 3. "multipart/form-data\"〉 4. 〈 inputid=\"FileUpLoad\"type=\" 5. file\"runat=\"server\"/〉〈 br/〉 6. 后台CS部分按钮事件 7. //stringstrFileFullName= 8. System.IO.Path.GetFileName(this. 9. FileUpLoad.PostedFile.FileName); 10. //this.FileUpLoad.PostedFile.SaveAs(Server.MapPath( 11. \"./Xmlzip/\")+strFileFullName); C#文件列表要点2.文件下载 1. ListBox的SelectedIndexChanged事件设 2. 定相关下载链接 3. protectedvoidlst_DownLoadFileList 4. _SelectedIndexChanged(objectsender,EventArgse) 5. { 6. try 7. { 8. stringstrJS=\"window.open(\'Xmlzip/\"; 9. strJS+=this.lst_DownLoadFileList. 10. SelectedItem.Text.Trim(); 11. strJS+=\"\');returnfalse;\"; 12. this.imgbtn_DownLoadFile.Attributes. 13. Add(\"onclick\",strJS); 14. } 15. catch(Exceptionex) 16. { 17. ex.ToString(); 18. } 19. } 20. 或者也能够经过改变Label的Text值来实现点击 21. 后实现文件下载的超级链接 22. this.Label1.Text=\"〈 ahref= 23. \\\"Xmlzip/a.rar\\\"〉a.rar〈 /a〉\" C#文件列表要点3.文件删除 1. stringstrFilePath=Server.MapPath( 2. \"../CountryFlowMgr/Xmlzip/\"+this.lst_ 3. DownLoadFileList.SelectedItem.Text.Trim()); 4. if(File.Exists(strFilePath)) 5. { 6. File.Delete(strFilePath); 7. if(File.Exists(strFilePath)) 8. { 9. Response.Write(\"ok\"); 10. } 11. else 12. { 13. Response.Write(\"ok\"); 14. } 15. } C#文件列表要点4.获得文件夹下的文件列表 1. #region获得当前可用的文件列表 2. ///〈 summary〉 3. ///获得当前可用的文件列表 4. ///〈 /summary〉 5. ///〈 paramname=\"IsAlert\"〉 6. 是否须要弹出提示信息〈 /param〉 7. privatevoidfn_getCurrFileList(boolIsAlert) 8. { 9. try 10. { 11. //查找Xmlzip文件夹下属于其本 12. 身UnitCoding的相关zip文件 13. stringstrXmlZipDirectory= 14. Server.MapPath(\"../Xmlzip/\"); 15. if(Directory.Exists(strXmlZipDirectory)) 16. { 17. //DirectoryInfodi=newDirectoryInfo( 18. Environment.CurrentDirectory); 19. DirectoryInfodi=newDirectoryInfo( 20. strXmlZipDirectory); 21. 22. FileInfo[]FI=di.GetFiles(\"*.zip\" 23. );//只查.zip文件 24. if(FI.Length〉0) 25. { 26. lst_DownLoadFileList.Items.Clear(); 27. foreach(FileInfotmpFIinFI) 28. { 29. ListItemtmpItem=newListItem(); 30. tmpItem.Text=tmpFI.Name; 31. lst_DownLoadFileList.Items.Add(tmpItem); 32. } 33. lst_DownLoadFileList.SelectedIndex=0; 34. } 35. else 36. { 37. if(IsAlert) 38. { 39. Response.write(\"查无能够下载的文件!\"); 40. } 41. } 42. } 43. } 44. catch(Exceptionex) 45. { 46. ex.ToString(); 47. } 48. } 49. #endregion
Color TabControl(C#)html
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace wgscd { public partial class myTabControl : TabControl { public myTabControl() { InitializeComponent(); this.DrawMode = TabDrawMode.OwnerDrawFixed;//必须 SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);//避免闪烁 UpdateStyles(); } protected Color HeaderBackColor1 = Color.DarkGreen; protected Color HeaderBackColor2 = Color.DarkKhaki; protected float headerbackangle = 45; protected Color titlebackcolor1 = Color.Bisque; protected Color titlebackcolor2 = Color.Blue; protected float titlebackangle = 45; protected Font headerfont = new Font("Arial", 12, FontStyle.Bold); protected StringAlignment titlealignment = StringAlignment.Center; protected Color headerfontcolor = Color.Plum; protected Font focusedheaderfont = new Font("Arial", 11, FontStyle.Regular); protected Color focusedheaderfontcolor = Color.PowderBlue; Rectangle r = new Rectangle(1, 1, 200, 200); protected override void OnPaint(PaintEventArgs e)//绘制整个TabControl控件背景不起做用。。。。。。。。。。。。 { r = new Rectangle(0, 0, this.Width, this.Height); Brush b = new SolidBrush(Color.Azure); Graphics g = e.Graphics; g.FillRectangle(b, r); // base.OnPaint(e); } protected override void OnDrawItem(DrawItemEventArgs e) { Graphics g = e.Graphics; Rectangle endPageRect = GetTabRect(TabPages.Count - 1); //最后一个标题栏的范围 Rectangle TitleRect = GetTabRect(e.Index); //当前标题栏的范围 Rectangle HeaderBackRect = Rectangle.Empty; //背景区域 switch (Alignment) { case TabAlignment.Top: HeaderBackRect = new Rectangle(new Point(endPageRect.X + endPageRect.Width, endPageRect.Y), new Size(Width - endPageRect.X - endPageRect.Width, endPageRect.Height)); break; case TabAlignment.Bottom: HeaderBackRect = new Rectangle(new Point(endPageRect.X + endPageRect.Width, endPageRect.Y), new Size(Width - endPageRect.X - endPageRect.Width, endPageRect.Height)); break; case TabAlignment.Left: HeaderBackRect = new Rectangle(new Point(endPageRect.X, endPageRect.Y + endPageRect.Height), new Size(endPageRect.Width, Height - endPageRect.Y - endPageRect.Height)); break; case TabAlignment.Right: HeaderBackRect = new Rectangle(new Point(endPageRect.X, endPageRect.Y + endPageRect.Height), new Size(endPageRect.Width, Height - endPageRect.Y - endPageRect.Height)); break; } Brush TitleBackBrush = new LinearGradientBrush(TitleRect, titlebackcolor1, titlebackcolor2, titlebackangle); //渐变角度 Font font = headerfont; StringFormat sf = new StringFormat(); sf.Alignment = titlealignment; sf.LineAlignment = StringAlignment.Center; Color fontcolor = headerfontcolor; if (SelectedIndex == e.Index) //若是绘制的标题就是选中的标题,则使用选中标题的字体,同时更新font和fontcolor { g.DrawRectangle(new Pen(TabPages[e.Index].BackColor), TitleRect); //消除选中标题的矩形方框 font = focusedheaderfont; fontcolor = focusedheaderfontcolor; } Brush fontbrush = new SolidBrush(fontcolor); //绘制标题文本 g.DrawString(TabPages[e.Index].Text, font, fontbrush, TitleRect, sf); //绘制背景 if (HeaderBackRect != Rectangle.Empty) { Brush HeaderBackBrush = new LinearGradientBrush(HeaderBackRect, HeaderBackColor1, HeaderBackColor2, headerbackangle); g.FillRectangle(HeaderBackBrush, HeaderBackRect); } // base.OnDrawItem(e); } } }
C#词法分析程序java
namespace 词法分析 { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.RichTextBox richTextBox1; private System.Windows.Forms.RichTextBox richTextBox2; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.SaveFileDialog saveFileDialog1; /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// <summary> /// 清理全部正在使用的资源。 /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.button2 = new System.Windows.Forms.Button(); this.richTextBox2 = new System.Windows.Forms.RichTextBox(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); this.button3 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(72, 24); this.label1.TabIndex = 0; this.label1.Text = "词法分析"; // // button1 // this.button1.Location = new System.Drawing.Point(240, 8); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(64, 23); this.button1.TabIndex = 1; this.button1.Text = "分析"; this.button1.Click += new System.EventHandler(this.button1_Click); // // richTextBox1 // this.richTextBox1.Location = new System.Drawing.Point(24, 48); this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.Size = new System.Drawing.Size(240, 352); this.richTextBox1.TabIndex = 2; this.richTextBox1.Text = ""; // this.richTextBox1.TextChanged += new System.EventHandler(this.richTextBox1_TextChanged); // // button2 // this.button2.Location = new System.Drawing.Point(96, 8); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(64, 23); this.button2.TabIndex = 3; this.button2.Text = "读入"; this.button2.Click += new System.EventHandler(this.button2_Click); // // richTextBox2 // this.richTextBox2.Location = new System.Drawing.Point(280, 48); this.richTextBox2.Name = "richTextBox2"; this.richTextBox2.Size = new System.Drawing.Size(280, 352); this.richTextBox2.TabIndex = 4; this.richTextBox2.Text = ""; // // button3 // this.button3.Location = new System.Drawing.Point(384, 8); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(56, 23); this.button3.TabIndex = 5; this.button3.Text = "保存"; this.button3.Click += new System.EventHandler(this.button3_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(584, 430); this.Controls.Add(this.button3); this.Controls.Add(this.richTextBox2); this.Controls.Add(this.button2); this.Controls.Add(this.richTextBox1); this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.MaximizeBox = false; this.Name = "Form1"; this.Text = "Form1"; // this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } /// <summary> /// 词法分析函数 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, System.EventArgs e) { //获得想要的字符数组。 char[] getch = textToCharArray(); //将字符数组,转换为词法分析后的 单词数组。 string[] stringArray = charArrayToStringArray(getch); //将单词数组分类,用数字标出各个单词所在的类别。 string[,] twoStringArray = stringArrayToTwoStringArray(stringArray); //用于输出二维数组。 printString(twoStringArray); } /// <summary> /// 输出结果 即用于输出二维数组。 /// </summary> /// <param name="twoStringArray"></param> private void printString(string[,] twoStringArray) { //提示说明 this.richTextBox2.Text = "1 -> 保留字" + "\r\n" + "2 -> 运算符" + "\r\n" + "3 -> 分隔符" + "\r\n" + "4 -> 数字 " + "\r\n" + "5 -> 其它" + "\r\n"; //输出二维数组中的数据 for (int x = 0; x < twoStringArray.Length / 2; x++) { for (int y = 0; y < 2; y++) { this.richTextBox2.Text = this.richTextBox2.Text + twoStringArray[y, x] + " "; if (y == 1) { this.richTextBox2.Text = this.richTextBox2.Text + "\r\n"; } } } } /// <summary> /// 打开方件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, System.EventArgs e)// 文件打开的方法。 { openFileDialog1.Filter = "文本文件(*.txt)|*.txt"; openFileDialog1.Title = "打开要分析的源文件。"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName); this.richTextBox1.Text = sr.ReadToEnd(); sr.Close(); } } /// <summary> /// 保存文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, System.EventArgs e) { saveFileDialog1.Filter = "文本文件(*.txt)|*.txt"; saveFileDialog1.Title = "保存分析结果."; if(saveFileDialog1.ShowDialog() == DialogResult.OK) { System.IO.StreamWriter wr = new System.IO.StreamWriter(saveFileDialog1.FileName); wr.Write(this.richTextBox2.Text); wr.Close(); } } /// <summary> /// 引用二维数组和单词的标志j /// </summary> /// <param name="twoArray"></param> /// <param name="j"></param> private void oneArrayToTwo(ref string[,] twoArray, ref int j) { string[,] tempArray = twoArray; twoArray = new string[2, j + 2]; for (int x = 0; x < 2; x++) { for (int y = 0; y < j + 1; y++) { twoArray[x, y] = tempArray[x, y]; } } j = j + 1; } /// <summary> /// 引用单词数组,和要加入单词数组的单词 /// </summary> /// <param name="stringArrange"></param> /// <param name="st"></param> private void stringToArrayString(ref string[] stringArrange, string st) { if (stringArrange[0] == "") { stringArrange[0] = st; } else { string[] oldA = stringArrange;//刚获得的字符串 int i = oldA.Length + 1; stringArrange = new string[i];//申请一个长一个的字符数组。 oldA.CopyTo(stringArrange, 0);//将先前的字符数组考到如今这个数组中。 stringArrange[stringArrange.Length - 1] = st; } } /// <summary> /// 将Text中的字符串,存入一个字符数组中。 /// </summary> /// <returns></returns> private char[] textToCharArray() { string stringTemp; stringTemp = this.richTextBox1.Text; char[] getch = stringTemp.ToCharArray();//要处理的字符都在getch这个数组中。 return getch; } /// <summary> /// 字符数组 到 单词数组 /// </summary> /// <param name="getch"></param> /// <returns></returns> private string[] charArrayToStringArray(char[] getch)//将字符数组转换为字符串数组。即词法分析后的单词数组。 { string[] stringArrange ={ "" };//用这个字符串数组存放词法分析后获得的单词。 char charTemp; string stringSave = "";// 存放一个分析获得的单词 //一次循环因获得一个单词。 for (int i = 0; i < getch.Length; i++) { charTemp = getch[i]; //由字母开头 数字和字母组成的单词。 if (charTemp >= 'a' && charTemp <= 'z' || charTemp >= 'A' && charTemp <= 'Z') { stringSave = charTemp.ToString(); i = i + 1; int test = 0;//判断循环是否结束,1 为结束。 while (test == 0) { charTemp = getch[i]; if (charTemp >= 'a' && charTemp <= 'z' || charTemp >= 'A' && charTemp <= 'Z' || charTemp >= '0' && charTemp <= '9') { stringSave = stringSave + charTemp.ToString(); i = i + 1; } else test = 1; } stringToArrayString(ref stringArrange, stringSave); } stringSave = ""; //由数字组成的单词。 if (charTemp >= '0' && charTemp <= '9') { stringSave = stringSave + charTemp.ToString(); i = i + 1; int test1 = 0; while (test1 == 0) { charTemp = getch[i]; if (charTemp >= '0' && charTemp <= '9') { stringSave = stringSave + charTemp.ToString(); i = i + 1; } else test1 = 1; } stringToArrayString(ref stringArrange, stringSave); } stringSave = ""; //由运算符组成的单词。 if (charTemp == '+' || charTemp == '-' || charTemp == '*' || charTemp == '/' || charTemp == '=' || charTemp == '<' || charTemp == '>' || charTemp == '!') { stringSave = stringSave + charTemp.ToString(); i = i + 1; int test2 = 0; while (test2 == 0) { charTemp = getch[i]; if (charTemp == '+' || charTemp == '-' || charTemp == '*' || charTemp == '/' || charTemp == '=' || charTemp == '<' || charTemp == '>' || charTemp == '!') { stringSave = stringSave + charTemp.ToString(); i = i + 1; } else test2 = 1; } stringToArrayString(ref stringArrange, stringSave); } stringSave = ""; //由介符组成的单词。 if (charTemp == '(' || charTemp == ')' || charTemp == '{' || charTemp == '}' || charTemp == '[' || charTemp == ']' || charTemp == ',' || charTemp == ':' || charTemp == ';' || charTemp == '"' || charTemp == '\'' || charTemp == '\\') { stringSave = stringSave + charTemp.ToString(); stringToArrayString(ref stringArrange, stringSave); } } return stringArrange; } /// <summary> /// 单词数组 到 二维单词数组。 /// </summary> /// <param name="stringArray"></param> /// <returns></returns> private string[,] stringArrayToTwoStringArray(string[] stringArray) { //存放单词标识后的结果。 string[,] twoArray = new string[2, 1]; //单词的标志 int j = 0; //每循环一次,把一个单词归于一类,即前面加上一个数字。 for (int i = 0; i < stringArray.Length; i++) { //保留字 1 if (stringArray[i] == "main" || stringArray[i] == "int" || stringArray[i] == "float" || stringArray[i] == "printf" || stringArray[i] == "if" || stringArray[i] == "for" || stringArray[i] == "while" || stringArray[i] == "do" || stringArray[i] == "return" || stringArray[i] == "break" || stringArray[i] == "continue") { twoArray[0, j] = "1"; twoArray[1, j] = stringArray[i]; this.oneArrayToTwo(ref twoArray, ref j); } //运算符 2 else if (stringArray[i] == "+" || stringArray[i] == "-" || stringArray[i] == "*" || stringArray[i] == "/" || stringArray[i] == ">" || stringArray[i] == "<" || stringArray[i] == ">=" || stringArray[i] == "<=" || stringArray[i] == "!=" || stringArray[i] == "==" || stringArray[i] == "++" || stringArray[i] == "--" || stringArray[i] == "=") { twoArray[0, j] = "2"; twoArray[1, j] = stringArray[i]; this.oneArrayToTwo(ref twoArray, ref j); } //分隔符 3 else if (stringArray[i] == "(" || stringArray[i] == ")" || stringArray[i] == "{" || stringArray[i] == "}" || stringArray[i] == "[" || stringArray[i] == "]" || stringArray[i] == "," || stringArray[i] == ";" || stringArray[i] == ":" || stringArray[i] == "\"" || stringArray[i] == "/*" || stringArray[i] == "*/") { twoArray[0, j] = "3"; twoArray[1, j] = stringArray[i]; this.oneArrayToTwo(ref twoArray, ref j); } //数字 4 else if (stringArray[i].ToCharArray()[0] >= '0' && stringArray[i].ToCharArray()[0] <= '9') { twoArray[0, j] = "4";//数字 twoArray[1, j] = stringArray[i]; this.oneArrayToTwo(ref twoArray, ref j); } //其它 5(变量等) else { twoArray[0, j] = "5"; twoArray[1, j] = stringArray[i]; this.oneArrayToTwo(ref twoArray, ref j); } } return twoArray; } } }
IMAP文件夹名称编码和解码方法web
// 编码 private string IMAPEncode(string folder) { string rtn = "", base64; int index = 0; Regex regAsis = new Regex(@"\G(?:[\x20-\x25\x27-\x7e])+"); Regex reg26 = new Regex(@"\G&"); Regex regEncode = new Regex(@"\G(?:[^\x20-\x7e])+"); Regex regEq = new Regex(@"=+$"); Regex regSlash = new Regex(@"\/"); while (index < folder.Length) { Match m; m = regAsis.Match(folder, index); if(m.Success) { index = index + m.Length; rtn = rtn + m.Value; continue; } m = reg26.Match(folder, index); if(m.Success) { index = index + m.Length; rtn = rtn + "&-"; continue; } m = regEncode.Match(folder, index); if(m.Success) { index = index + m.Length; base64 = Convert.ToBase64String(Encoding.GetEncoding("UTF-16BE").GetBytes(m.Value)); base64 = regEq.Replace(base64, ""); base64 = regSlash.Replace(base64, ","); rtn = rtn + "&" + base64 + "-"; continue; } } return rtn; } // 解码 private string IMAPDeconde(string folder) { string rtn = "", base64; int index = 0; Regex regAsis = new Regex(@"\G([^&]+)"); Regex reg26 = new Regex(@"\G\&-"); Regex regDecode = new Regex(@"\G\&([A-Za-z0-9+,]+)-?"); Regex regComma = new Regex(@","); while (index < folder.Length) { Match m; m = regAsis.Match(folder, index); if(m.Success) { index = index + m.Length; rtn = rtn + m.Value; continue; } m = reg26.Match(folder, index); if(m.Success) { index = index + m.Length; rtn = rtn + "&"; continue; } m = regDecode.Match(folder, index); if(m.Success) { index = index + m.Length; base64 = m.Value.Substring(1, m.Value.Length - 2); base64 = regComma.Replace(base64, "/"); int mod = base64.Length % 4; if(mod > 0 ) base64 = base64.PadRight(base64.Length + (4 - mod), '='); base64 = Encoding.GetEncoding("UTF-16BE").GetString(Convert.FromBase64String(base64)); rtn = rtn + base64; continue; } } return rtn; }
MFC选项卡的实现数据库
方案一 在对话框上放置一个Tab Control的控件,再在对话框上放置所需的控件(本例放置了2个按钮,试图在每一个标签中显示一个)。而后利用Class Wizard来为Tab Control控件建立一个控件变量,该变量是CTabCtrl类的,再为其余控件也建立相应的控件类。 在主对话框的初始函数中CProperty1Dlg::OnInitDialog()加入以下代码: //本例插入两个标签,实际运用中可经过循环插入所需个数的标签,运行后默认第一个标签被选中 m_tab.InsertItem( 0, _T("Tab1") ); m_tab.InsertItem( 1, _T("Tab2") ); //将不是第一个标签的控件隐藏掉,只留下你要的控件 m_button2.ShowWindow( SW_HIDE ); 再利用ClassWizard处理Tab Control的 TCN_SELCHANGE 的消息。在消息处理函数中,利用CWnd::ShowWindow来使相应的控件显示和隐藏。 void CProperty1Dlg::OnSelchangeTab1(NMHDR* pNMHDR, LRESULT* pResult) { //GetCurSel返回当前被选中的标签的索引号(以0为基础算起) int sel = m_tab.GetCurSel(); switch(sel) { case 0: m_button1.ShowWindow( SW_SHOW ); m_button2.ShowWindow( SW_HIDE ); break; case 1: m_button2.ShowWindow( SW_SHOW ); m_button1.ShowWindow( SW_HIDE ); break; } *pResult = 0; } 方案二 本这个方案中,我将使用MFC中现成的CPropertySheet和CPropertyPage类来完成将控件分散到各个对话框类中。 首先加入两个(或数个)对话框资源。修改各对话框资源的属性,将对话框的Caption属性改成你要在标签上所显示的文字。将对话框的Style属性改成:Child, Border属性改成:Thin, 只选中Title Bar复选框,去掉其余复选框。而后你能够在这些对话框中加入要分开显示的各个控件。 为上述对话框资源分别制做一个对话框类,该对话框类是从CPropertyPage继承。这样一来各子对话框类就行了,主对话框类能够直接使用CPropertySheet类。使用以下代码便可: CPropertySheet sheet("属性页对话框"); CPage1 page1; CPage2 page2; //加入子对话框做为一个属性页 sheet.AddPage(&page1); sheet.AddPage(&page2); //产生一个模态对话框,也可使用Create方法来产生一个非模态对话框(具体参见MSDN) sheet.DoModal(); 如何在主对话框中放置其余控件呢?若是直接使用CPropertySheet的话,是不能够的,可是别忘了咱们能够从CPropertySheet类继承本身的类啊! 方案三 首先仍是要建立那些要在属性页中的显示的子对话框类,建立步骤和方案二同样,都是从CPropertyPage继承。 此次咱们将从CPropertySheet类继承本身的类(假设类名为CMySheet)。咱们要在这里放上一个button控件。那么如今先在CMySheet中加入一个CButton类的成员变量m_button。 在CMySheet类中的OnInitDialog()函数里,这样写: BOOL bResult = CPropertySheet::OnInitDialog(); //取得属性页的大小 CRect rectWnd; GetWindowRect(rectWnd); //调整对话框的宽度 SetWindowPos(NULL, 0, 0,rectWnd.Width() + 100,rectWnd.Height(),SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); CRect rectButton(rectWnd.Width() + 25, 25,rectWnd.Width()+75, 75); //用程序建立一个按钮 m_button.Create("Button", BS_PUSHBUTTON, CRect(rectWnd.Width(), 25,rectWnd.Width()+75, 50) , this, 1); //显示这个按钮 m_button.ShowWindow( SW_SHOW ); CenterWindow(); return bResult; 使用方案三虽然能在主对话框中加入控件,可是也比较麻烦,首先所加的控件只能在属性页的右边或下边。而且用程序来产生控件比较烦琐,位置与大小不易控制。那么还有其余方法,既能在对话框中加入属性页,又能在主对话框随意添加控件? 方案四 不从CPropertySheet继承本身的类,仍是直接使用它。各属性页的子对话框类仍是须要的,建立方法和上述两个方案相同。 首先咱们新建一个基于对话框的工程。在编辑已有的一个主对话框中能够自由加一些所需的控件,可是得留出必定的空间用于放置属性页。 在主对话框类里加入一个CPropertySheet类的一个成员变量(m_sheet)表明整个属性页。再加入一些各子对话框类的实例做为成员变量(m_page一、m_page2……)。 在主对话框类的OnInitDialog()函数中加入: //加入标签,标签名由各个子对话框的标题栏决定 m_sheet.AddPage(&m_page1); m_sheet.AddPage(&m_page2); //用Create来建立一个属性页 m_sheet.Create(this, WS_CHILD | WS_VISIBLE, WS_EX_CONTROLPARENT); RECT rect; m_sheet.GetWindowRect(&rect); int width = rect.right - rect.left; int height = rect.bottom - rect.top; //调整属性页的大小和位置 m_sheet.SetWindowPos(NULL, 20, 50, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); 这个方案能够自由在主对话框中加一些必要的控件,并且属性页中的控件也都分散在了各个子对话框类中,使用很是方便。 方案五 使用Tab Control,而且从CTabCtrl控件类继承本身的类(CTabSheet)来处理。 首先我先介绍一下如何使用CTabSheet。 先要制做子对话框类,此次的子对话框类不要从CPropertyPage继承,而是直接从CDialog继承。而且各个子对话框资源的属性应设置为:Style为Child, Border为None。 在主对话框资源中,加入一个Tab Control,而且适当调整位置和大小。利用ClassWizard来为这个Tab Control建立一个CTabSheet的控件变量。 在主对话框的OnInitDialog()加入: m_sheet.AddPage("tab1", &m_page1, IDD_DIALOG1); m_sheet.AddPage("tab2", &m_page2, IDD_DIALOG2); m_sheet.Show(); 就这样就能够在对话框上制做出一个完美的属性页了。效果和上图彻底同样。 下面我就来说讲CTabSheet类的细节内容。 CTabSheet是从CTabCtrl继承来的,用于Tab Control的控件类。在类中有一个成员变量用来记录各子对话框的指针CDialog* m_pPages[MAXPAGE]; MAXPAGE是该类所能加载的标签的最大值。 类中有一个AddPage方法,用于记录子对话框的指针和所使用对话框资源的ID号。 BOOL CTabSheet::AddPage(LPCTSTR title, CDialog *pDialog,UINT ID) { if( MAXPAGE == m_nNumOfPages ) return FALSE; //保存目前总的子对话框数 m_nNumOfPages++; //记录子对话框的指针、资源ID、要在标签上显示的文字 m_pPages[m_nNumOfPages-1] = pDialog; m_IDD[m_nNumOfPages-1] = ID; m_Title[m_nNumOfPages-1] = title; return TRUE; } 在使用AddPage加入了若干子对话框后,必须调用CTabSheet的Show方法来真正生成标签和子对话框。 void CTabSheet::Show() { //利用CDialog::Create来建立子对话框,而且使用CTabCtrl::InsertItem来加上相应的标签 for( int i=0; i < m_nNumOfPages; i++ ) { m_pPages[i]->Create( m_IDD[i], this ); InsertItem( i, m_Title[i] ); } //因为对话框显示时默认的是第一个标签被选中,因此应该让第一个子对话框显示,其余子对话框隐藏 m_pPages[0]->ShowWindow(SW_SHOW); for( i=1; i < m_nNumOfPages; i++) m_pPages[i]->ShowWindow(SW_HIDE); SetRect(); } 生成好标签和子对话框后,调用CTabSheet::SetRect来计算并调整属性页的大小。 void CTabSheet::SetRect() { CRect tabRect, itemRect; int nX, nY, nXc, nYc; //获得Tab Control的大小 GetClientRect(&tabRect); GetItemRect(0, &itemRect); //计算出各子对话框的相对于Tab Control的位置和大小 nX=itemRect.left; nY=itemRect.bottom+1; nXc=tabRect.right-itemRect.left-2; nYc=tabRect.bottom-nY-2; //利用计算出的数据对各子对话框进行调整 m_pPages[0]->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_SHOWWINDOW); for( int nCount=1; nCount < m_nNumOfPages; nCount++ ) m_pPages[nCount]->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_HIDEWINDOW); } 在单击标签栏后,应该是相应的子对话框显示,正在显示的子对话框应该隐藏。所以利用ClassWizard来处理WM_LBUTTONDOWN消息。 void CTabSheet::OnLButtonDown(UINT nFlags, CPoint point) { CTabCtrl::OnLButtonDown(nFlags, point); //判断是否单击了其余标签 if(m_nCurrentPage != GetCurFocus()) { //将原先的子对话框隐藏 m_pPages[m_nCurrentPage]->ShowWindow(SW_HIDE); m_nCurrentPage=GetCurFocus(); //显示当前标签所对应的子对话框 m_pPages[m_nCurrentPage]->ShowWindow(SW_SHOW); } } 这样利用CTabSheet这个类就能够轻松地在对话框上放置本身的属性页了,而且控件都分散在各子对话框类中,符合对象封装的思想。并且用这个方法来制做属性页就能够利用ClassWizard来轻松地生成消息映射处理Tab Control的消息了。例如:能够处理TCN_SELCHANGE消息来对切换了标签时进行一些动做。 方案五另外一写法 思路:当咱们调用InsertItem()这个函数的时候,选项卡控件将会添加一个标签页,这个时候,咱们将本身的对话框的窗体的指针与此标签页关联起来,当用户进行标签页的切换的时候,咱们根据当前是哪一个标签页,显示哪一个对话框,不是与当前标签页关联的对话框,咱们将其隐藏便可.这样咱们即可以实现选项卡控件. 第一步:新建一个本身的类CTabSheet继承CTabCtrl. 第二步:定义有用的成员变量 CDialog* m_dlgWnd[MAXTABPAGE]; //这个是存放对话框指针的指针数组 int m_curTabNumber; //记录当前用户添加了几个标签页 int m_selTabID; //当前用户点击的标签页的ID 第三步:添加成员函数 //经过这个函数,能够将一个对话框指针与添加的标签页关联起来,insWnd是建立的非模式对话框的指针,wndID是对话框的ID,pageText是标签页的标题 void CreateTabPage(CWnd *insWnd, int wndID,CString pageText) //添加控件的点击事件的处理,当点击后获得当前点击的标签页的ID,而后将与此标签页相关的对话框显示,其它的隐藏便可 void OnLButtonDown(UINT nFlags, CPoint point) 经过添加以上的成员变量及成员函数便可实现一个简单的选项卡控件的用法 下面我将这两个成员函数的代码贴出来,并详细讲解 //建立而且增长一个标签页 //建立而且增长一个标签页 void CTabSheet::CreateTabPage(CWnd *insWnd, int wndID,CString pageText) { if (m_curTabNumber >= MAXTABPAGE) { MessageBox("标签页己经达到最大!","建立出错!",MB_OK); return; } //首先new一个对话框的指针,可是不要调用create函数,再将些指针当成参数传进来便可,建立己由此函数作完 if (NULL == insWnd) { MessageBox("标签页为空","建立出错",MB_OK); return; } //建立对话框,而且增长标签页 CDialog* curDlg = (CDialog*)insWnd; curDlg->Create(wndID,this); int suc = InsertItem(m_curTabNumber,pageText); if (-1 == suc) { MessageBox("插入标签页失败","失败",MB_OK); return; } curDlg->ShowWindow(SW_SHOW); //将这个对应的窗体指针存放起来 m_dlgWnd[m_curTabNumber] = curDlg; //此时选择当前页面 SetCurSel(m_curTabNumber); m_selTabID = m_curTabNumber; m_curTabNumber ++; } //点击左键事件,处理 void CTabSheet::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CTabCtrl::OnLButtonDown(nFlags, point); //获得当前用户点击的标签页的ID int curSelect = GetCurSel(); //获得当前标签页的位置以便设置对话框显示的位置 CRect curRect; GetClientRect(curRect); if (-1 == curSelect) { return; } //查找标签页,将与当前用户点击的标签页相关的对话框显示出来,其它的对话框隐藏 for (int i = 0; i < m_curTabNumber; i ++) { if (i == curSelect) { m_dlgWnd[i]->SetWindowPos(NULL,0,20,curRect.Width(),curRect.bottom,SWP_SHOWWINDOW); } else { m_dlgWnd[i]->SetWindowPos(NULL,0,20,curRect.Width(),curRect.bottom,SWP_HIDEWINDOW); } } m_selTabID = curSelect; Invalidate(); //CTabCtrl::OnLButtonDown(nFlags, point); } 以上为关键的两个函数,下面介绍调用的方法 建立非模式的对话框 CTabSheet m_tabSheet; CMyDlg* m_dlg = new CMyDlg; m_tabSheet.CreateTabPage(m_dlg ,IDD_DLG_ID,"第一个标签页"); 这样就能够产生一个标签页了,固然还能够继续调用此函数添加标签页 本文根据网上的资料整理,如下是用方案五写的一个实例程序。 来自:http://c.chinaitlab.com/vc/838702.html
Net下几种日志管理方法express
日志是应用程序中不可缺乏的一部份,不只能够记录应用程序的运行状态,还能够记录一些BUG,便于应用程序的更新与修改。 在.Net有好几种方法能够对日志进行管理。 1、数据库日志。 2、文本日志。 3、系统事件日志。 首先,对于数据库日志而言,它的使用简单并且方便。这里就不作太多的讨论,相信写过与数据相关的项目的人都会用数据来记录一些日志。然而它惟一很差的就是:必须先保证你的数据库连接是正确无误的。 然而这一保证不是必然的,因此这里我再讨论一下其它的两种状况,文本日志及系统事件日志。 文本日志: 它使用简单,并且查看也方便。很差的就是不便于作大量的日志,并且日志内容的查看与分析都不方便。然而它仍是可在在一些不适合数据库日志的地方使用。例如一些测试消息的输出,一些独立组件的少许日志等。 通常状况下,为了方便管理,以天为单位对日志文件进行分类。这样一来也能够简单的对文件进行管理。例如:你的文件名能够知道这个日志是何时的,而后能够简单的作一个相似数据库同样的查询,管理也还方便。毕竟文本对系统来讲是如此的简单。 .Net有一个诊断类,能够把文本以监听的方式添加到Trace以及Debug上,这样一来,你的全部指向Trace和Degug的输出都会记录到文件里去。这是一个很不错的方法。 using System.Diagnostics; Debug.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(DateTime.Now.ToString("yyyyMMdd")+"..log")); Debug.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(Console.Out)); 或者: Trace.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(DateTime.Now.ToString("yyyyMMdd")+"..log")); Trace.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(Console.Out)); 这里的区别是:Trace在Release下可使用,而Debug只在Debug下使用。 我以为全部的文本日志中,上面的方法是最好用的。你只需要再作一个日志管理的类就好了。 固然,还要注意,就是监听在24小时后要更新一次,应该把当前的监听清理掉,而后从新添加一个。这也简单。 另外一个方法就是本身写文本进行管理。这样的方法要略麻烦一点点,道也不难。 然而文本日志除了不便于作大量日志的工做以还,还有一个致命的问题:进程冲突! 由于文本日志要锁定正在写的文本文件,因此其它要写该文件的程序会出现错误。通常状况下,若是应该程序只有一个副本在运行,并且把日志作为一个全局的静态对象来处理,也不会有什么太大的问题。但程序的第二个副本会由于文件不能打开而启动失败。 这并非一个没法解决的问题,只用保证程序有一个副本就好了。若是不保证的话,那么小有一点复杂,这里就再也不讨论了,下次有机会再讨论这个问题。 对于上面的问题,我想暂时放弃文本日志,用系统的事件日志来处理。 系统事件日志: .net下有一个EventLog类,它直接与系统的事件日志关联。 简单的一个: EventLog.WriteEntry("LogSource","This is a test log."); 就能够往系统里写一个事件了。 然而把它用好也还有点点麻烦。首先是上面的方法会在系统的Application下写一个事件日志,并且为默认为Information类型。这样很不利于管理,你们能够在管理工具里看一下日志,就会发现大量的日志,本身写的一个小日志简直没法找到。 然而.Net为咱们提供了几个方法来更好的管理日志。 1、添加一个新的LogSource。 什么是LogSource?其实简单的说,它就是日志的一个分类标记,例如你能够用程序一次取出因此LogSource为指定内容的日志。这样一来,只要你记得这个Source名,你就能够读取和分类管理日志了。 默认状况下,你在直接用EventLog的静态函数写日志的时候,要指定一个LogSource,若是LogSource不存在,那么它就自动在Application下创建一个,所以,建立LogSource就这么简单了。 2、添加一个新的Log. 什么是Log.这里的Log是指系统事件日志里的大日志分类,通常状况下,系统有Application,System和Sercuity三个日志,每一个下面有不一样的Soucce,这样就构成了日志系统。 你不能独立的建立一个Log,由于.NET里没有提供任何方法来建立一个Log,只能经过函数:CreateEventSource(string,string) 来建立一个Sourcce,此时若是你这样作:CreateEventSource("MySource","MyLog"); 你就会在日志管理器里看到多了一个MyLog类,然而再这样写日志: EventLog.WriteEntry("MySource","This is a test log."); 就能够写一条记录到MyLog分类下,这样就能够很好的管理本身的日志了。 须要说明的是: 若是Source已经存在,那么建立会失败。注意:无论Source的哪一个Log下,只要Source的名字已经存在,那么你的建立都会失败。例如:若是有一个"Source1"的日志在Application里,那么你就不能再到其它Log里再建立一个名为"Source1"的日志了。另外:你用程序建立的日志不能在日志管理器里删除它(Messages能够删除,但日志分类不能删除)。方法是你仍是用程序能够来删除,或者在注册表里来删除它。它的位置:[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\] 看一下注册表,或许你会明白一些。 最后就是用日志实例对象来写日志。你能够指定一个Log名和一个Source名来写日志,但要注意,必须是Log与Source匹配,不然也会出现错误。这比直接用静态方法来写日志要复杂一点点,但你有更多的自由空间。 系统事件日志很差的地方就是日志只保存三个月,并且很差管理。若是你能够直接管理服务器,或者就在本机上运行应该会好一些,不然你就不得不本身写些代码来管理日志了。固然,若是一些重要的日志,能够导出到其它文件中。 它的好处是不少的: 1、没必要与数据库连接,效率会高一些,也不会有数据库访问失败的问题。 2、不会有进程冲突问题,它是系统的日志,无论是什么应用程序均可以写日志。 3、全局可用,无论在哪里均可以直接写日志,并且可读。所以能够把它当成一个消息通讯平台。(固然,可能只有那些大脑有点问题的人会这样作。)然而我只是想说明:A进程写的日志,B进程能够直接读取。 好了,关于日志此次就总结这些。
VC 给Tab控件的标签贴图canvas
设置TAB标题前的小图标: HIMAGELIST hImageList = ImageList_Create(24,24,ILC_COLOR32,0,2); HICON himodify = (HICON)LoadImage(NULL,TEXT("res\\Pictures.ico"),IMAGE_ICON,24,24,LR_LOADFROMFILE); ImageList_AddIcon(hImageList , himodify); TabCtrl_SetImageList(hTabCtrl ,hImageList); TCITEM tabitem; tabitem.mask = TCIF_TEXT | TCIF_IMAGE ; tabitem.pszText = TEXT("1"); tabitem.iImage = 0; TabCtrl_InsertItem(hTabCtrl,0,&tabitem); 或者采用: void CFormTabView::OnInitialUpdate() { m_imagelist.Create(16,16,ILC_MASK,4,4);//建立图标 HICON hIcon; //hIcon = ::LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_ICON1)); hIcon = AfxGetApp()->LoadIcon(IDI_ICON_LEDON);// icon 0 m_imagelist.Add(hIcon); hIcon = AfxGetApp()->LoadIcon(IDI_ICON_LEDOFF);//icon 1 m_imagelist.Add(hIcon); CRect rect; GetClientRect(rect); rect.top += 0; m_ctTab.MoveWindow(rect); m_ctTab.SetImageList(&m_TabImageList); m_ctTab.InsertItem(TCIF_TEXT | TCIF_IMAGE,0,"page0",0,0);//选择的是icon 0,倒数第二个参数 m_ctTab.InsertItem(TCIF_TEXT | TCIF_IMAGE,1,"page1",1,0);//选择的是icon 1 m_ctTab.InsertItem(TCIF_TEXT | TCIF_IMAGE,2,"page2",1,0);//选择的是icon 1 m_ctTab.InsertItem(TCIF_TEXT | TCIF_IMAGE,3,"page3",1,0);//选择的是icon 1 // m_ctTab.HighlightItem(0); // m_ctTab.SetPadding(CSize(3,3)); int x; x = (rect.Width()-10)/m_ctTab.GetItemCount(); m_ctTab.SetItemSize(CSize(x,20)); ....... } m_imagelist 是 view/dialog成员变量CImageList m_ctTab 是 tabctrl控件映射的变量 用image 的话是同样的,也用cimagelist 参考:http://topic.csdn.net/t/20050415/16/3939802.html
WinForms C#:html编辑器工程源码,含直接写WebBrowser的文件流、IPersistStreamInit接口的声明和一些相关的小方法c#
首先多谢朋友们的捧场; 今天给你们带来一个操做WebBrowser的一些高级方法,我专门写了一个html编辑器的实现代码,有须要的朋友能够本身扩充; 功能实现是直接写流到WebBrowser内不经过临时文件,而且支持对WebBrowser的一些高级控制(其实script能够达到的都可达到,想知道怎么搞的能够阅读代码)。 其中关于IPersistStreamInit接口的声明费了翻工夫,由于之前在 delphi 中没这么麻烦,呵呵。在网络上找了大半天没找到,最后仍是祭出Reflector,反编译Windows.Forms,须要的朋友能够不用辛苦的本身搞了! 我在这个演示里,制做的html编辑环境是比简单的,您能够看看,比较比较 CodeProject 上的代码;我采用的是ie自身提供的编辑方法,只是这样的方式都被运用于web方式的编辑器内,就比如这个freeTextBox 如下是主要的代码: 1 /******************************** 2 * 初始化浏览器状态 3 * 指向about:blank 4 * *****************************/ 5 private void Form1_Load(object sender, System.EventArgs e) { 6 object obj = null; 7 this.Show(); 8 this.axWb.Navigate("about:blank",ref obj,ref obj,ref obj,ref obj); 9 //等待完成动做 10 while(axWb.ReadyState < SHDocVw.tagREADYSTATE.READYSTATE_INTERACTIVE) 11 Application.DoEvents(); 12 13 //初始化html编辑器 14 InitHtmlEditor(); 15 } 16 17 /******************************* 18 * 这里是核心方法 19 * 彻底调用IE自身的html编辑功能 20 * 能够看到,我采用了一种兼容的 21 * 方式,用Frame(框架),这样 22 * 的话,默认安装的Windows 98都 23 * 支持html编辑功能; 24 * 关键代码以下: 25 * frame.document.designMode = "on"; 26 * 表示开启设计模式 27 ******************************/ 28 private void InitHtmlEditor(){ 29 string sw = ""; 30 sw += "<html>\r\n"; 31 sw += "<script language=javascript>\r\n"; 32 sw += " function loadSet(){\r\n"; 33 sw += " var frame=document.getElementById(\"i-frame\").contentWindow;\r\n"; 34 sw += " frame.document.designMode = \"on\";\r\n"; 35 sw += " frame.document.open();\r\n"; 36 sw += " frame.document.write(\"<html><font color=red>hello 你们好啊!<br>我是S.F. <br>"; 37 sw += " <a href=\\\"http://www.cnblogs.com/chinasf\\\">欢迎访问个人weblog</a></font></html>\");\r\n"; 38 sw += " frame.document.close();\r\n"; 39 sw += " }\r\n"; 40 sw += " function setBlod(obj){\r\n"; 41 sw += " document.getElementById(\"i-frame\").contentWindow.document.execCommand(\"bold\");\r\n"; 42 sw += " }\r\n"; 43 sw += "</script>\r\n"; 44 //这里加入了一个html的button,也就是说,你能够把web模式的html编辑器的代码彻底copy进来 45 sw += "<body onload=\"loadSet()\" scroll=\"yes\"><button onclick=\"setBlod(this);\">Blod</button>\r\n"; 46 sw += "<iframe id=\"i-frame\" frameBorder=\"1\" width=\"640\" height=\"480\"></iframe>\r\n"; 47 sw += "</body></html>\r\n"; 48 49 //写入浏览器 50 WriteHtml(sw); 51 } 52 53 private void WriteHtml(string s){ 54 //内存流,用于转换string 55 MemoryStream ms = new MemoryStream(); 56 try{ 57 byte[] htmlcode = System.Text.Encoding.Default.GetBytes(s); 58 ms.Write(htmlcode,0,htmlcode.Length); 59 Stream dataStream = ms; 60 //恢复指针位置 61 dataStream.Seek(0,0); 62 63 if(axWb.Document!=null){ 64 //转换接口,并转换为IStream 65 (axWb.Document as UnsafeNativeMethods.IPersistStreamInit).Load(new UnsafeNativeMethods.ComStreamFromDataStream(dataStream)); 66 } 67 }finally{ 68 ms.Close(); 69 } 70 } 71 72 private void button1_Click(object sender, System.EventArgs e) { 73 //获取document,在IHTMLDocument2中取得桢 74 mshtml.IHTMLDocument3 idoc = (mshtml.IHTMLDocument3)axWb.Document; 75 mshtml.IHTMLFrameBase2 fb= (mshtml.IHTMLFrameBase2)idoc.getElementById("i-frame"); 76 object obj=null; 77 fb.contentWindow.document.execCommand("bold",true,obj); 78 } 79 80 private void button3_Click(object sender, System.EventArgs e) { 81 //获取document,在IHTMLDocument2中才有body.style 82 mshtml.IHTMLDocument2 idoc = (mshtml.IHTMLDocument2)axWb.Document; 83 //指定为IHTMLStyle3,才能够定制滚动条颜色 84 mshtml.IHTMLStyle3 istyle = (mshtml.IHTMLStyle3)idoc.body.style; 85 istyle.scrollbarArrowColor = "#0099FF"; 86 istyle.scrollbar3dLightColor = "#FFFFFF"; 87 istyle.scrollbarDarkShadowColor = "#0099FF"; 88 istyle.scrollbarFaceColor = "#99CCFF"; 89 istyle.scrollbarHighlightColor = "#0099FF"; 90 istyle.scrollbarShadowColor = "#0099FF"; 91 istyle.scrollbarTrackColor = "#FFFFFF"; 92 93 } 94 95 private void button2_Click(object sender, System.EventArgs e) { 96 //查看源码,文本方式 97 mshtml.IHTMLDocument3 idoc = (mshtml.IHTMLDocument3)axWb.Document; 98 mshtml.IHTMLFrameBase2 fb= (mshtml.IHTMLFrameBase2)idoc.getElementById("i-frame"); 99 MessageBox.Show(fb.contentWindow.document.body.innerText); 100 } 101 102 private void button4_Click(object sender, System.EventArgs e) { 103 //查看源码,HTML方式 104 mshtml.IHTMLDocument3 idoc = (mshtml.IHTMLDocument3)axWb.Document; 105 mshtml.IHTMLFrameBase2 fb= (mshtml.IHTMLFrameBase2)idoc.getElementById("i-frame"); 106 MessageBox.Show(fb.contentWindow.document.body.innerHTML); }
UDP打洞原理及代码设计模式
UDP"打洞"原理 1. NAT分类 根据Stun协议(RFC3489),NAT大体分为下面四类 1) Full Cone 这种NAT内部的机器A链接过外网机器C后,NAT会打开一个端口.而后外网的任何发到这个打开的端口的UDP数据报均可以到达A.无论是否是C发过来的. 例如 A:192.168.8.100 NAT:202.100.100.100 C:292.88.88.88 A(192.168.8.100:5000) -> NAT(202.100.100.100 : 8000) -> C(292.88.88.88:2000) 任何发送到 NAT(202.100.100.100:8000)的数据均可以到达A(192.168.8.100:5000) 2) Restricted Cone 这种NAT内部的机器A链接过外网的机器C后,NAT打开一个端口.而后C能够用任何端口和A通讯.其余的外网机器不行. 例如 A:192.168.8.100 NAT:202.100.100.100 C:292.88.88.88 A(192.168.8.100:5000) -> NAT(202.100.100.100 : 8000) -> C(292.88.88.88:2000) 任何从C发送到 NAT(202.100.100.100:8000)的数据均可以到达A(192.168.8.100:5000) 3) Port Restricted Cone 这种NAT内部的机器A链接过外网的机器C后,NAT打开一个端口.而后C能够用原来的端口和A通讯.其余的外网机器不行. 例如 A:192.168.8.100 NAT:202.100.100.100 C:292.88.88.88 A(192.168.8.100:5000) -> NAT(202.100.100.100 : 8000) -> C(292.88.88.88:2000) C(202.88.88.88:2000)发送到 NAT(202.100.100.100:8000)的数据均可以到达A(192.168.8.100:5000) 以上三种NAT通称Cone NAT.咱们只能用这种NAT进行UDP打洞. 4) Symmetic 对于这种NAT.链接不一样的外部目标.原来NAT打开的端口会变化.而Cone NAT不会.虽然能够用端口猜想.可是成功的几率很小.所以放弃这种NAT的UDP打洞. 2. UDP hole punching 对于Cone NAT.要采用UDP打洞.须要一个公网机器C来充当”介绍人”.内网的A,B先分别和C通讯.打开各自的NAT端口.C这个时候知道A,B的公网IP: Port. 如今A和B想直接链接.好比A给B发.除非B是Full Cone.不然不能通讯.反之亦然.可是咱们能够这样. A要链接B.A给B发一个UDP包.同时.A让那个介绍人给B发一个命令,让B同时给A发一个UDP包.这样双方的NAT都会记录对方的IP,而后就会容许互相通讯. 3. 同一个NAT后面的状况 若是A,B在同一个NAT后面.若是用上面的技术来进行互连.那么若是NAT支持loopback(就是本地到本地的转换),A,B能够链接,可是比较浪费带宽和NAT.有一种办法是,A,B和介绍人通讯的时候,同时把本身的local IP也告诉服务器.A,B通讯的时候,同时发local ip和公网IP.谁先到就用哪一个IP.可是local ip就有可能不知道发到什么地方去了.好比A,B在不一样的NAT后面可是他们各自的local ip段同样.A给B的local IP发的UDP就可能发给本身内部网里面的某某某了. 还有一个办法是服务器来判断A,B是否在一个NAT后面.(网络拓朴不一样会不会有问题?) WellKnown.cs //WellKnown公用库 using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Net; using System.Net.Sockets; using System.Collections; namespace P2PWellKnown { /// <summary> /// UDP用户登陆事件委托 /// </summary> /// <param name="sender">事件源对象</param> /// <param name="e">事件实体</param> public delegate void UdpUserLogInDelegate(object sender, UDPSockEventArgs e); /// <summary> /// 通常UDP消息事件委托 /// </summary> /// <param name="sender">事件源对象</param> /// <param name="e">事件实体</param> public delegate void UdpMessageDelegate(object sender, UDPSockEventArgs e); /// <summary> /// 初始化一个新链接的事件委托 /// </summary> /// <param name="sender">事件源对象</param> /// <param name="e">事件实体</param> public delegate void UdpNewConnectDelegate(object sender, UDPSockEventArgs e); /// <summary> /// P2P共享数据类 /// </summary> public class P2PConsts { /// <summary> /// UDP服务器监听端口 /// </summary> public const int UDP_SRV_PORT = 2280; /// <summary> ///TCP服务器监听端口 /// </summary> public const int TCP_SRV_PORT = 2000; } /// <summary> /// FormatterHelper 序列化,反序列化消息的帮助类 /// </summary> public class FormatterHelper { public static byte[] Serialize(object obj) { BinaryFormatter binaryF = new BinaryFormatter(); MemoryStream ms = new MemoryStream(1024 * 10); binaryF.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin); byte[] buffer = new byte[(int)ms.Length]; ms.Read(buffer, 0, buffer.Length); ms.Close(); return buffer; } public static object Deserialize(byte[] buffer) { BinaryFormatter binaryF = new BinaryFormatter(); MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length, false); object obj = binaryF.Deserialize(ms); ms.Close(); return obj; } } /// <summary> /// 用于承载UDPSock信息的事件类 /// </summary> public class UDPSockEventArgs : EventArgs { /// <summary> /// 要承载的消息 /// </summary> private string m_strMsg; /// <summary> /// 用户信息 /// </summary> private string m_strUserName; /// <summary> /// 触发该事件的公共终端 /// </summary> private IPEndPoint m_EndPoint; /// <summary> /// 初始化UDPSock事件 /// </summary> /// <param name="sMsg">用户发送的信息</param> public UDPSockEventArgs(string sMsg) : base() { this.m_strMsg = sMsg; } /// <summary> /// 远端用户名 /// </summary> public string RemoteUserName { get { return m_strUserName; } set { m_strUserName = value; } } /// <summary> /// 通常套接字消息 /// </summary> public string SockMessage { get { return m_strMsg; } set { m_strMsg = value; } } /// <summary> /// 公共远端节点 /// </summary> public IPEndPoint RemoteEndPoint { get { return m_EndPoint; } set { m_EndPoint = value; } } } } UDPP2PSock.cs //UDPP2PSock.cs using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using P2PWellKnown; namespace UDPP { /// <summary> /// UDPP2P套接字管理类 /// </summary> public class UDPP2PSock { /// <summary> /// 用户登陆事件 /// </summary> public event UdpUserLogInDelegate OnUserLogInU; /// <summary> /// 通常UDP消息事件 /// </summary> public event UdpMessageDelegate OnSockMessageU; /// <summary> /// 初始化一个新链接事件 /// </summary> public event UdpNewConnectDelegate OnNewConnectU; /// <summary> /// UDP服务器 /// </summary> private UdpClient m_udpServer; /// <summary> /// UDP客户端 /// </summary> private UdpClient m_udpClient; /// <summary> /// 服务器实际上在本地机器上监听的 /// 端口,用于当一台计算机上同时启 /// 动两个可两以上服务器进程时,标 /// 识不一样的服务器进程 /// </summary> private int m_iMyServerPort; /// <summary> /// 客户端在本地机器上实际使用的端口, /// 用于当一台计算机上同时有两个或两 /// 个以上客户端进程在运行时,标识不 /// 同的客户端进程 /// </summary> private int m_iMyClientPort; /// <summary> /// 标识是否已成功创服务器 /// </summary> private bool m_bServerCreated; /// <summary> /// 标识是否已成功建立客户端 /// </summary> private bool m_bClientCreated; /// <summary> /// 服务器使用的线程 /// </summary> private Thread m_serverThread; /// <summary> /// 客户端使用的线程 /// </summary> private Thread m_clientThread; /// <summary> /// 打洞线程 /// </summary> //private Thread m_burrowThread; /// <summary> /// 远端节点 /// </summary> private IPEndPoint m_remotePoint; /// <summary> /// 当前进程做为客户端的公共终端 /// </summary> private string m_strMyPublicEndPoint; /// <summary> /// 当前进程做为客户端的私有终端 /// </summary> private string m_strMyPrivateEndPoint; /// <summary> /// 用于接受信息的 StringBuilder实例 /// </summary> private StringBuilder m_sbResponse = new StringBuilder(); /// <summary> /// P2P打洞时标识是否收到回应消息 /// </summary> private bool m_bRecvAck = false; /// <summary> /// 请求向其方向打洞的私有终端 /// </summary> private IPEndPoint m_requestPrivateEndPoint; /// <summary> /// 请求向其方向打洞的公共终端 /// </summary> private IPEndPoint m_requestPublicEndPoint; /// <summary> /// 打洞消息要发向的节点 /// </summary> private ToEndPoint m_toEndPoint; /// <summary> /// 用于标识是否已经和请求客户端创建点对链接 /// </summary> //private bool m_bHasConnected=false ; /// <summary> /// 建立服务器或客户端的最大尝试 /// 次数,为(65536-60000),防止 /// 因不能建立而限入死循环或使用 /// 无效端口 /// </summary> private const int MAX_CREATE_TRY = 5536; /// <summary> /// 打洞时尝试链接的最大尝试次数 /// </summary> private const int MAX_CONNECT_TRY = 10; /// <summary> /// 构造函数,初始化UDPP2P实例 /// </summary> public UDPP2PSock() { m_iMyServerPort = P2PConsts.UDP_SRV_PORT; m_iMyClientPort = 60000; m_bClientCreated = false; m_bServerCreated = false; m_toEndPoint = new ToEndPoint(); m_serverThread = new Thread(new ThreadStart(RunUDPServer)); m_clientThread = new Thread(new ThreadStart(RunUDPClient)); //m_burrowThread = new Thread(new ThreadStart(BurrowProc)); } /// <summary> /// 建立UDP 服务器 /// </summary> public void CreateUDPSever() { int iTryNum = 0; //开始尝试建立服务器 while (!m_bServerCreated && iTryNum < MAX_CREATE_TRY) { try { m_udpServer = new UdpClient(m_iMyServerPort); m_bServerCreated = true; } catch { m_iMyServerPort++; iTryNum++; } } //建立失败,抛出异常 if (!m_bServerCreated && iTryNum == MAX_CREATE_TRY) { throw new Exception("建立服务器尝试失败!"); } m_serverThread.Start(); } /// <summary> /// 建立UDP客户端 /// </summary> /// <param name="strServerIP"& gt;服务器IP</param> /// <param name="iServerPort"& gt;服务器端口</param> public void CreateUDPClient(string strServerIP, int iServerPort) { int iTryNum = 0; //开始尝试建立服务器 while (!m_bClientCreated && iTryNum < MAX_CREATE_TRY) { try { m_udpClient = new UdpClient(m_iMyClientPort); m_bClientCreated = true; string strIPAddress = (System.Net.Dns.GetHostAddresses("localhost")[0]).ToString(); m_strMyPrivateEndPoint = strIPAddress + ":" + m_iMyClientPort.ToString(); } catch { m_iMyClientPort++; iTryNum++; } } //建立失败,抛出异常 if (!m_bClientCreated && iTryNum == MAX_CREATE_TRY) { throw new Exception("建立客户端尝试失败!"); } IPEndPoint hostPoint = new IPEndPoint(IPAddress.Parse(strServerIP), iServerPort); string strLocalIP = (System.Net.Dns.GetHostAddresses("localhost"))[0].ToString(); SendLocalPoint(strLocalIP, m_iMyClientPort, hostPoint); m_clientThread.Start(); } /// <summary> /// 运行UDP 服务器 /// </summary> private void RunUDPServer() { while (true) { byte[] msgBuffer = m_udpServer.Receive(ref m_remotePoint); m_sbResponse.Append(System.Text.Encoding.Default.GetString(msgBuffer)); CheckCommand(); Thread.Sleep(10); } } /// <summary> /// 运行UDP客户端 /// </summary> private void RunUDPClient() { while (true) { byte[] msgBuffer = m_udpClient.Receive(ref m_remotePoint); m_sbResponse.Append(System.Text.Encoding.Default.GetString(msgBuffer)); CheckCommand(); Thread.Sleep(10); } } /// <summary> /// 销毁UDP 服务器 /// </summary> public void DisposeUDPServer() { m_serverThread.Abort(); m_udpServer.Close(); } /// <summary> /// 销毁UDP客房端 /// </summary> public void DisposeUDPClient() { m_clientThread.Abort(); m_udpClient.Close(); } /// <summary> /// 发送消息 /// </summary> /// <param name="strMsg"& gt;消息内容</param> /// <param name="REP"& gt;接收节点</param> public void SendData(string strMsg, IPEndPoint REP) { byte[] byMsg = System.Text.Encoding.Default.GetBytes(strMsg.ToCharArray()); m_udpClient.Send(byMsg, byMsg.Length, REP); } /// <summary> /// 发送消息,服务器专用 /// </summary> /// <param name="strMsg"& gt;消息内容</param> /// <param name="REP"& gt;接收节点</param> private void ServerSendData(string strMsg, IPEndPoint REP) { byte[] byMsg = System.Text.Encoding.Default.GetBytes(strMsg.ToCharArray()); m_udpServer.Send(byMsg, byMsg.Length, REP); } /// <summary> /// 发送本地节点信息 /// </summary> /// <param name="strLocalIP"& gt;本地IP</param> /// <param name="iLocalPort"& gt;本地端口</param> public void SendLocalPoint(string strLocalIP, int iLocalPort, IPEndPoint REP) { string strLocalPoint = "\x01\x02" + strLocalIP + ":" + iLocalPort.ToString() + "\x02\x01"; SendData(strLocalPoint, REP); } /// <summary> /// 同时向指定的终端(包括公共终端和私有终端)打洞 /// </summary> /// <param name="pubEndPoint"& gt;公共终端</param> /// <param name="prEndPoint"& gt;私有终端</param> /// <returns>打洞成功返回true,不然返回false</returns> public void StartBurrowTo(IPEndPoint pubEndPoint, IPEndPoint prEndPoint) { Thread burrowThread = new Thread(new ThreadStart(BurrowProc)); m_toEndPoint.m_privateEndPoint = prEndPoint; m_toEndPoint.m_publicEndPoint = pubEndPoint; burrowThread.Start(); } /// <summary> /// 打洞线程 /// </summary> private void BurrowProc() { IPEndPoint prEndPoint = m_toEndPoint.m_privateEndPoint; IPEndPoint pubEndPoint = m_toEndPoint.m_publicEndPoint; int j = 0; for (int i = 0; i < MAX_CONNECT_TRY; i++) { SendData("\x01\x07\x07\x01", prEndPoint); SendData("\x01\x07\x07\x01", pubEndPoint); // 等待接收线程标记修改 for (j = 0; j < MAX_CONNECT_TRY; j++) { if (m_bRecvAck) { m_bRecvAck = false; SendData("\x01\x07\x07\x01", prEndPoint); Thread.Sleep(50); SendData("\x01\x07\x07\x01", pubEndPoint); UDPSockEventArgs args = new UDPSockEventArgs(""); args.RemoteEndPoint = pubEndPoint; if (OnNewConnectU != null) { OnNewConnectU(this, args); } //Thread .Sleep (System .Threading.Timeout .Infinite ); return; } else { Thread.Sleep(100); } } //若是没有收到目标主机的回应,代表本次打 // 洞尝试失败,等待100毫秒后尝试下一次打洞 Thread.Sleep(100); } //MAX_CONNECT_TRY 尝试都失败,代表打洞失败,抛出异常 //throw new Exception(" 打洞失败!"); System.Windows.Forms.MessageBox.Show("打洞失败!");//////////// } /// <summary> /// 转发打洞请求消息,在服务器端使用 /// </summary> /// <param name="strSrcPrEndpoint"& gt;请求转发的源私有终端</param> /// <param name="strSrcPubEndPoint"& gt;请求转发的源公共终端</param> /// <param name="REP"& gt;转发消息到达的目的终端</param> public void SendBurrowRequest(string strSrcPrEndpoint, string strSrcPubEndPoint, IPEndPoint REP) { string strBurrowMsg = "\x04\x07" + strSrcPrEndpoint + " " + strSrcPubEndPoint + "\x07\x04"; ServerSendData(strBurrowMsg, REP); } /// <summary> /// 检查字符串中的命令 /// </summary> private void CheckCommand() { int nPos; string strCmd = m_sbResponse.ToString(); //若是接收远端用户名 if ((nPos = strCmd.IndexOf("\x01\x02")) > -1) { ReceiveName(strCmd, nPos); // 反馈公共终给端远端主机 string strPubEPMsg = "\x03\x07" + m_remotePoint.ToString() + "\x07\x03"; SendData(strPubEPMsg, m_remotePoint); return; } //若是接收个人公共终端 if ((nPos = strCmd.IndexOf("\x03\x07")) > -1) { ReceiveMyPublicEndPoint(strCmd, nPos); return; } //若是是打洞请求消息 if ((nPos = strCmd.IndexOf("\x04\x07")) > -1) { ReceiveAndSendAck(strCmd, nPos); return; } //若是是打洞回应消息 if ((nPos = strCmd.IndexOf("\x01\x07")) > -1) { m_bRecvAck = true; int nPos2 = strCmd.IndexOf("\x07\x01"); if (nPos2 > -1) { m_sbResponse.Remove(nPos, nPos2 - nPos + 2); } return; } //通常聊天消息 m_sbResponse.Remove(0, strCmd.Length); RaiseMessageEvent(strCmd); } /// <summary> /// 接收远端用户名 /// </summary> /// <param name="strCmd"& gt;包含用户名的控制信息</param> /// <param name="nPos"></param> private void ReceiveName(string strCmd, int nPos) { int nPos2 = strCmd.IndexOf("\x02\x01"); if (nPos2 == -1) { return; } m_sbResponse.Remove(nPos, nPos2 - nPos + 2); string strUserName = strCmd.Substring(nPos + 2, nPos2 - nPos - 2); UDPSockEventArgs e = new UDPSockEventArgs(""); e.RemoteUserName = strUserName; e.RemoteEndPoint = m_remotePoint; //触发用户登陆事件 if (OnUserLogInU != null) { OnUserLogInU(this, e); } } /// <summary> /// 接收打洞请求的消息并发送回应 /// </summary> /// <param name="strCmd"></param> /// <param name="nPos"></param> private void ReceiveAndSendAck(string strCmd, int nPos) { int nPos2 = strCmd.IndexOf("\x07\x04"); if (nPos2 == -1) { return; } m_sbResponse.Remove(nPos, nPos2 - nPos + 2); string strBurrowMsg = strCmd.Substring(nPos + 2, nPos2 - nPos - 2); string[] strSrcPoint = strBurrowMsg.Split(' '); //分析控制字符串包含的节点信息 string[] strPrEndPoint = strSrcPoint[0].Split(':'); string[] strPubEndPoint = strSrcPoint[1].Split(':'); m_requestPrivateEndPoint = new IPEndPoint(IPAddress.Parse(strPrEndPoint[0]), int.Parse(strPrEndPoint[1])); m_requestPublicEndPoint = new IPEndPoint(IPAddress.Parse(strPubEndPoint[0]), int.Parse(strPubEndPoint[1])); //向请求打洞终端的方向打洞 StartBurrowTo(m_requestPublicEndPoint, m_requestPrivateEndPoint); } /// <summary> /// 接收个人公共终端 /// </summary> /// <param name="strCmd"& gt;包含公共终端的控制信息</param> /// <param name="nPos"& gt;控制字符串的起始位置</param> private void ReceiveMyPublicEndPoint(string strCmd, int nPos) { int nPos2 = strCmd.IndexOf("\x07\x03"); if (nPos2 == -1) { return; } m_sbResponse.Remove(nPos, nPos2 - nPos + 2); m_strMyPublicEndPoint = strCmd.Substring(nPos + 2, nPos2 - nPos - 2); } /// <summary> /// 触发通常UDP消息事件 /// </summary> /// <param name="strMsg"& gt;消息内容</param> private void RaiseMessageEvent(string strMsg) { UDPSockEventArgs args = new UDPSockEventArgs(""); args.SockMessage = strMsg; args.RemoteEndPoint = m_remotePoint; if (OnSockMessageU != null) { OnSockMessageU(this, args); } } /// <summary> /// 获取当前进程做为客户端的公共终端 /// </summary> public string MyPublicEndPoint { get { return m_strMyPublicEndPoint; } } /// <summary> /// 获取当前进程做为客户端的私有终端 /// </summary> public string MyPrivateEndPoint { get { return m_strMyPrivateEndPoint; } } } /// <summary> /// 保存打洞消息要发向的节点信息 /// </summary> class ToEndPoint { /// <summary> /// 私有节点 /// </summary> public IPEndPoint m_privateEndPoint; /// <summary> /// 公共节点 /// </summary> public IPEndPoint m_publicEndPoint; } } 关于如何使用上述程序包的一些说明: 主要程序的初始化,参考代码以下: using UDPP; using P2PWellKnown; //建立UDP服务器和客户端 try { string strServerIP = "127.0.0.1"; UDPP2PSock udpSock = new UDPP2PSock(); udpSock.OnUserLogInU += new UdpUserLogInDelegate(OnUserLogInU); udpSock.OnNewConnectU += new UdpNewConnectDelegate(OnNewConnectU); udpSock.CreateUDPSever(); udpSock.CreateUDPClient(strServerIP, P2PConsts.UDP_SRV_PORT); } catch (Exception ex) { } 经上面的初始化后,就可使用类UDPP2PSock中的方法了。 注: udpSock.OnUserLogInU += new UdpUserLogInDelegate(OnUserLogInU); udpSock.OnNewConnectU += new UdpNewConnectDelegate(OnNewConnectU); 中的OnUserLogInU和OnNewConnectU是事件名称 如 private void test(object sender, UDPSockEventArgs e) { MessageBox.Show("ok"); } 个性签名:作要作好,作到不伦不类不如不作。
c# 中如何结束进程explorer.exe数组
foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcesses()) { if(thisproc.ProcessName.Equals("explorer")) { thisproc.Kill(); } }
c#换ip代理源码
不少朋友都想如何提升本身的网站流量,但是都没有什么好的办法 通过很长时间的研究,在C#中实现了,固然了,这部分代码其中一部分是网上的,不是原创。 using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Runtime.InteropServices; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using System.Text; using System.Net; namespace WebSock { /// <summary> /// Form1 的摘要说明。 /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.GroupBox groupBox1; private AxSHDocVw.AxWebBrowser axWebBrowser1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.Timer timer1; private System.ComponentModel.IContainer components; private System.Windows.Forms.StatusBar statusBar1; private System.Windows.Forms.StatusBarPanel statusBarPanel1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.Button button3; ArrayList arrText = new ArrayList(); int Total = 0; int i,k=0; private System.Windows.Forms.GroupBox groupBox5; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtWebUrl; private const string TitleInfo = "程序制做红色银狐"; private System.Windows.Forms.ListBox listBox1; private string strUrl = ""; public Form1() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// <summary> /// 清理全部正在使用的资源。 /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.axWebBrowser1 = new AxSHDocVw.AxWebBrowser(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.listBox1 = new System.Windows.Forms.ListBox(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.statusBar1 = new System.Windows.Forms.StatusBar(); this.statusBarPanel1 = new System.Windows.Forms.StatusBarPanel(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.button3 = new System.Windows.Forms.Button(); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.txtWebUrl = new System.Windows.Forms.TextBox(); this.groupBox1.SuspendLayout(); this.groupBox3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).BeginInit(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).BeginInit(); this.groupBox4.SuspendLayout(); this.groupBox5.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.groupBox3); this.groupBox1.Controls.Add(this.groupBox2); this.groupBox1.Location = new System.Drawing.Point(0, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(810, 440); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; // // groupBox3 // this.groupBox3.Controls.Add(this.axWebBrowser1); this.groupBox3.Location = new System.Drawing.Point(312, 8); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(490, 424); this.groupBox3.TabIndex = 2; this.groupBox3.TabStop = false; this.groupBox3.Text = "浏览器"; // // axWebBrowser1 // this.axWebBrowser1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.axWebBrowser1.ContainingControl = this; this.axWebBrowser1.Enabled = true; this.axWebBrowser1.Location = new System.Drawing.Point(8, 16); this.axWebBrowser1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axWebBrowser1.OcxState"))); this.axWebBrowser1.Size = new System.Drawing.Size(474, 400); this.axWebBrowser1.TabIndex = 0; // // groupBox2 // this.groupBox2.Controls.Add(this.listBox1); this.groupBox2.Location = new System.Drawing.Point(8, 8); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(296, 424); this.groupBox2.TabIndex = 1; this.groupBox2.TabStop = false; this.groupBox2.Text = "代理IP地址"; // // listBox1 // this.listBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.listBox1.ItemHeight = 12; this.listBox1.Location = new System.Drawing.Point(8, 16); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(280, 398); this.listBox1.TabIndex = 2; // // button1 // this.button1.Location = new System.Drawing.Point(310, 16); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(176, 32); this.button1.TabIndex = 1; this.button1.Text = "载入代理IP"; this.button1.Click += new System.EventHandler(this.button1_Click_1); // // button2 // this.button2.Location = new System.Drawing.Point(486, 16); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(176, 32); this.button2.TabIndex = 2; this.button2.Text = "开始刷流量"; this.button2.Click += new System.EventHandler(this.button2_Click); // // timer1 // this.timer1.Interval = 10000; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // statusBar1 // this.statusBar1.Dock = System.Windows.Forms.DockStyle.None; this.statusBar1.Location = new System.Drawing.Point(0, 552); this.statusBar1.Name = "statusBar1"; this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] { this.statusBarPanel1}); this.statusBar1.ShowPanels = true; this.statusBar1.Size = new System.Drawing.Size(810, 24); this.statusBar1.TabIndex = 3; // // statusBarPanel1 // this.statusBarPanel1.Width = 820; // // groupBox4 // this.groupBox4.Controls.Add(this.button3); this.groupBox4.Controls.Add(this.button2); this.groupBox4.Controls.Add(this.button1); this.groupBox4.Location = new System.Drawing.Point(0, 496); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(810, 56); this.groupBox4.TabIndex = 4; this.groupBox4.TabStop = false; this.groupBox4.Text = "操做区"; // // button3 // this.button3.Location = new System.Drawing.Point(134, 16); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(176, 32); this.button3.TabIndex = 3; this.button3.Text = "从网络获取代理IP"; this.button3.Click += new System.EventHandler(this.button3_Click); // // groupBox5 // this.groupBox5.Controls.Add(this.label1); this.groupBox5.Controls.Add(this.txtWebUrl); this.groupBox5.Location = new System.Drawing.Point(0, 444); this.groupBox5.Name = "groupBox5"; this.groupBox5.Size = new System.Drawing.Size(810, 48); this.groupBox5.TabIndex = 5; this.groupBox5.TabStop = false; this.groupBox5.Text = "要刷网站地址"; // // label1 // this.label1.Location = new System.Drawing.Point(16, 21); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(56, 16); this.label1.TabIndex = 1; this.label1.Text = "网站地址"; // // txtWebUrl // this.txtWebUrl.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtWebUrl.Location = new System.Drawing.Point(80, 16); this.txtWebUrl.Name = "txtWebUrl"; this.txtWebUrl.Size = new System.Drawing.Size(720, 21); this.txtWebUrl.TabIndex = 0; this.txtWebUrl.Text = "http://www.51solve.com/"; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(810, 575); this.Controls.Add(this.groupBox5); this.Controls.Add(this.groupBox4); this.Controls.Add(this.statusBar1); this.Controls.Add(this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "网站流量访问程序制做:红色银狐"; this.groupBox1.ResumeLayout(false); this.groupBox3.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).EndInit(); this.groupBox2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).EndInit(); this.groupBox4.ResumeLayout(false); this.groupBox5.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } //定义结构体代理信息 public struct Struct_INTERNET_PROXY_INFO { public int dwAccessType; public IntPtr proxy; public IntPtr proxyBypass; }; [DllImport("wininet.dll", SetLastError = true)] private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength); private void RefreshIESettings(string strProxy) { const int INTERNET_OPTION_PROXY = 38; const int INTERNET_OPEN_TYPE_PROXY = 3; Struct_INTERNET_PROXY_INFO struct_IPI; // Filling in structure struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY; struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy); struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local"); // Allocating memory IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI)); // Converting structure to IntPtr Marshal.StructureToPtr(struct_IPI, intptrStruct, true); bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI)); } private void StartShua() { statusBar1.Panels[0].Text = "正在使用" + arrText[k].ToString() + "代理IP访问网站"; this.listBox1.SetSelected(k,true); RefreshIESettings(arrText[k].ToString()); System.Object nullObject = 0; string strTemp = String.Empty; System.Object nullObjStr = strTemp; axWebBrowser1.Navigate(strUrl, ref nullObject, ref nullObjStr, ref nullObjStr, ref nullObjStr); k+=1; if(k>=i)k=0; } private void button1_Click_1(object sender, System.EventArgs e) { arrText.Clear(); i = 0; if(openFileDialog1.ShowDialog() ==DialogResult.OK) { string strPath,strLine = ""; strPath = openFileDialog1.FileName.ToString(); StreamReader sr = new StreamReader(strPath); while(strLine != null) { strLine = sr.ReadLine(); if(strLine != null) { i+=1; arrText.Add(strLine); listBox1.Items.Add(strLine); } } sr.Close(); } } private void timer1_Tick(object sender, System.EventArgs e) { StartShua(); } private void button2_Click(object sender, System.EventArgs e) { Total = listBox1.Items.Count; strUrl = txtWebUrl.Text; if(button2.Text == "开始刷流量") { if(i == 0 && Total == 0)return; if(strUrl.Length == 0)return; StartShua(); button2.Text = "中止刷流量"; timer1.Enabled = true; timer1.Start(); button1.Enabled = false; button3.Enabled = false; } else { timer1.Stop(); timer1.Enabled = false; button2.Text = "开始刷流量"; button1.Enabled = true; button3.Enabled = true; arrText.Clear(); } } private void button3_Click(object sender, System.EventArgs e) { arrText.Clear(); i = 0; listBox1.Items.Clear(); string strHtml = ""; string strPort = ""; string strResultIP = ""; long PosB = 0; long PosA = 0; long PosC = 0; string Url = "http://www.pass-e.com/proxy/"; try { strHtml = GetHtml(Url); strHtml = checkStr(strHtml); strHtml = strHtml.ToLower(); PosA = strHtml.IndexOf("list",0); //MessageBox.Show(GetHtml(Url)); while(PosA>0) { i+=1; PosB = strHtml.IndexOf(",",(int)PosA); strResultIP = strHtml.Substring((int)PosA,(int)PosB-(int)PosA); strResultIP = strResultIP.Replace("list",""); PosC = strHtml.IndexOf(",",(int)PosB+1); strPort = strHtml.Substring((int)PosB,(int)PosC-(int)PosB); strPort = strPort.Replace(",",""); listBox1.Items.Add(strResultIP+":"+strPort); PosA = strHtml.IndexOf("list",(int)PosC); arrText.Add(strResultIP+":"+strPort); } } catch(Exception ex) { MessageBox.Show(ex.Message,TitleInfo,MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } public string checkStr(string html) { string str = Convert.ToString((char)34); Regex regex1 = new Regex(@"<mce:script[/s/S]+</script *><!-- ", RegexOptions.IgnoreCase); Regex regex2 = new Regex(@" href *= *[/s/S]*script *:", RegexOptions.IgnoreCase); Regex regex3 = new Regex(@" no[/s/S]*=", RegexOptions.IgnoreCase); Regex regex4 = new Regex(@"<iframe[/s/S]+</iframe *>", RegexOptions.IgnoreCase); Regex regex5 = new Regex(@"<frameset[/s/S]+</frameset *>", RegexOptions.IgnoreCase); Regex regex6 = new Regex(@"/<img[^/>]+/>", RegexOptions.IgnoreCase); Regex regex7 = new Regex(@"</p>", RegexOptions.IgnoreCase); Regex regex8 = new Regex(@"<p>", RegexOptions.IgnoreCase); Regex regex9 = new Regex(@"<[^>]*>", RegexOptions.IgnoreCase); html = html.Replace("/r/n",""); //html = regex1.Replace(html, ""); //过滤<script> // --></mce:script>标记 html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 html = regex4.Replace(html, ""); //过滤iframe html = regex5.Replace(html, ""); //过滤frameset html = regex6.Replace(html, ""); //过滤frameset html = regex7.Replace(html, ""); //过滤frameset html = regex8.Replace(html, ""); //过滤frameset html = regex9.Replace(html, ""); html = html.Replace(" ", ""); html = html.Replace("</strong>", ""); html = html.Replace("<strong>", ""); html = html.Replace("/n",""); html = html.Replace(str ,""); html = html.Replace("}" ,""); html = html.Replace("(" ,""); html = html.Replace(")" ,""); //html = html.Replace(";" ,""); html = html.Replace("'" ,""); html = html.Replace(" " ,""); html = html.Replace(" ",""); return html; } public string GetHtml(string myUrl) { HttpWebRequest myHttpWebRequest; HttpWebResponse myHttpWebResponse; //string Html; try { string URL = myUrl; Uri myUri = new Uri(myUrl); WebRequest myWebRequest = WebRequest.Create(URL); //使用Creat方法建立WebRequest实例 myHttpWebRequest = (HttpWebRequest)myWebRequest; //实现WebRequest类型和HttpWebRequest类型的转换 WebResponse myWebResponse = myHttpWebRequest.GetResponse(); //得到响应信息 myHttpWebResponse = (HttpWebResponse)myWebResponse; Stream myStream = myHttpWebResponse.GetResponseStream(); //得到从当前Internet资源返回的响应流数据 StreamReader srReader = new StreamReader(myStream, Encoding.Default); //利用得到的响应流和系统缺省编码来初始化StreamReader实例。 string sTemp = srReader.ReadToEnd(); //从响应流从读取数据 srReader.Close(); return sTemp; } //显示读取的数据 ( ) catch (WebException WebExcp) { return WebExcp.Message.ToString(); } } } } 经过它的实现,只要你有足够的代理IP那么你的网站流量变飞速的提高。
c#中WinForm的TextBox循环自动滚动示例
这个问题来自论坛提问,演示代码以下 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsApplication27 { /// <summary> /// 演示如何在TextBox中让文字循环滚动: /// 做者jinjazz /// 做者blog:http://blog.csdn.net/jinjazz /// </summary> public partial class Form1 : Form { public Form1() { InitializeComponent(); this.textBox1.Clear(); for (int i = 0; i <= 20;i++ ) { this.textBox1.Text += string.Format("{0}:jinjazz__{1} ", i,i); } this.timer1.Interval = 200; this.timer1.Start(); } //发送消息 [DllImport("user32.dll", EntryPoint = "SendMessage")] public static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam); //获取滚动条位置 [DllImport("user32")] public static extern int GetScrollPos(IntPtr hwnd, int nBar); //设置滚动条位置 [DllImport("user32.dll")] static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw); public const int EM_LINESCROLL = 0xb6; private void timer1_Tick(object sender, EventArgs e) { int i= GetScrollPos(this.textBox1.Handle,1); //向下滚动一行 SendMessage(this.textBox1.Handle, EM_LINESCROLL, 0, 1);//0,1表明垂直滚动条向下滚动 //判断是否有位置变化,若是没有则说明到了底部,返回开始处 if (i == GetScrollPos(this.textBox1.Handle, 1)) { //回到顶部,这里用SetScrollPos彷佛有问题,滚动条和文字不是同步更新 this.textBox1.SelectionStart = 0; this.textBox1.SelectionLength = 1; this.textBox1.ScrollToCaret(); this.textBox1.SelectionLength = 0; } Console.WriteLine(i); } private void textBox1_MouseEnter(object sender, EventArgs e) { this.timer1.Stop(); } private void textBox1_MouseLeave(object sender, EventArgs e) { this.timer1.Start(); } } }
wpf翻页效果
教你打造Silverlight超酷翻页实例 做者:洗碗心得 | 出处:博客园 | 2011/10/18 19:47:52 | 阅读22次 常常阅读电子杂志的朋友对其流畅天然的翻页过渡效果应当留下了十分深入的印象。这些杂志都是使用Flash技术制做而成的。总想着能用Silverlight实现这样的效果,去网上查查资料,找到了一个微软官方提供的翻页效果例子(教程说明点这里,在线实例演示及源代码下载点这里)。这里再推荐一个外国网站的Silverlight翻页在线实例。 效果是十分的赞,只惋惜控制的逻辑是用JavaScript代码实现的,这就不利于程序逻辑的总体控制。笔者最近在CodePlex上,找到了一个开源的翻页控件WPF and Silverlight BookControls(点这里进入),用它进行Silverlight翻页效果的开发就显得十分驾轻就熟了。下面就向你们一步一步地介绍Silverlight翻页效果的实现过程。 导航: ①创建翻页项目解决方案 ②添加必要文件 ③构建应用程序界面 ④设置应用程序控制逻辑 ⑤最终效果图 1、创建翻页项目解决方案 点击File->Projects...菜单选项,新建一个ASP.NET Web Application。 将新建工程名称命名为FlipPage。 在解决方案下继续添加一个Silverlight应用程序项目,将该工程命名为SilverlightClient。 在弹出的对话框中,直接点OK按钮。 点击一下“所有保存”按钮,完成项目工程的建立。 2、添加必要文件 在SilverlightClient项目文件夹下,新建一个名为Dll的文件夹,在里面放入WPF and Silverlight BookControls的动态连接库文件SLMitsuControls.dll(以下图)。在FlipPage项目文件夹下,新建一个名为mediaPictures的子文件夹,在里面放入将在书中显示的图片,以下图所示命名。一样的,在SilverlightClient项目文件夹下,新建一个名为PageType的文件夹,而后再新建两个类分别命名为LeftPage.cs和RightPage.cs(以下图),它们分别表明了书的偶数和奇数页面,具体代码以下所示(详细的说明请见代码注释)。 LeftPage.cs文件代码: Code System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace SilverlightClient.TypePage { public class LeftPage : Canvas { //定义将在页面上显示的元素 private Image imgPhoto; private Button btnPrevious; private Rectangle RecBorder; private TextBlock PageNum; //构造函数 public LeftPage() { //页面的设置 this.Width = 452; this.Height = 630; this.Background = new SolidColorBrush(Colors.White); Canvas.SetLeft(this, 0); Canvas.SetTop(this, 0); //页面边框的设置 RecBorder = new Rectangle(); RecBorder.Width = 452; RecBorder.Height = 630; Canvas.SetLeft(RecBorder, 0);//设置页面边框在Canvas中的位置,下同。 Canvas.SetTop(RecBorder, 0); RecBorder.Stroke = new SolidColorBrush(Colors.Black); RecBorder.StrokeThickness = 0; this.Children.Add(RecBorder); //照片的设置 imgPhoto = new Image(); imgPhoto.Width = 450; imgPhoto.Height = 600; Canvas.SetLeft(imgPhoto, 1); Canvas.SetTop(imgPhoto, 1); this.Children.Add(imgPhoto); //“前一页”按钮的设置 btnPrevious = new Button(); btnPrevious.Width = 150; btnPrevious.Height = 20; btnPrevious.Content = "<< 前一页"; btnPrevious.HorizontalContentAlignment = HorizontalAlignment.Center; btnPrevious.VerticalContentAlignment = VerticalAlignment.Center; btnPrevious.Cursor = Cursors.Hand; Canvas.SetLeft(btnPrevious, 151); Canvas.SetTop(btnPrevious, 605); this.Children.Add(btnPrevious); //页码文本的设置 PageNum = new TextBlock(); PageNum.Width = 100; PageNum.Height = 20; PageNum.Text = "00 / 00"; PageNum.TextAlignment = TextAlignment.Left; PageNum.VerticalAlignment = VerticalAlignment.Center; PageNum.FontFamily = new FontFamily("Comic sans MS"); Canvas.SetLeft(PageNum, 10); Canvas.SetTop(PageNum, 607); this.Children.Add(PageNum); } //设置图片路径 public void setterimgPhoto(string path) { BitmapImage btm = new BitmapImage(); btm.UriSource = new Uri(path, UriKind.Relative); imgPhoto.Source = btm; } //设置按钮是否可见 public void setterDisplayBtnPrevious(bool YesNo) { if (YesNo) { btnPrevious.Visibility = Visibility.Visible; } else { btnPrevious.Visibility = Visibility.Collapsed; } } //设置页码 public void setterPageNumber(string currentPageNum, string TotalPageNum) { PageNum.Text = currentPageNum + " / " + TotalPageNum; } //返回按钮单击事件关联 public Button getbtnPrevious() { return btnPrevious; } } } RightPage.cs文件代码: Code System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace SilverlightClient.TypePage { public class RightPage : Canvas { //定义将在页面上显示的元素 private Image imgPhoto; private Button btnNext; private Rectangle RecBorder; private TextBlock PageNum; //构造函数 public RightPage() { //页面的设置 this.Width = 452; this.Height = 630; this.Background = new SolidColorBrush(Colors.White); Canvas.SetLeft(this, 0);//设置页面边框在Canvas中的位置,下同。 Canvas.SetTop(this, 0); //页面边框的设置 RecBorder = new Rectangle(); RecBorder.Width = 452; RecBorder.Height = 630; Canvas.SetLeft(RecBorder, 0); Canvas.SetTop(RecBorder, 0); RecBorder.Stroke = new SolidColorBrush(Colors.Black); RecBorder.StrokeThickness = 0; this.Children.Add(RecBorder); //照片的设置 imgPhoto = new Image(); imgPhoto.Width = 450; imgPhoto.Height = 600; Canvas.SetLeft(imgPhoto, 1); Canvas.SetTop(imgPhoto, 1); this.Children.Add(imgPhoto); //“后一页”按钮的设置 btnNext = new Button(); btnNext.Width = 150; btnNext.Height = 20; btnNext.Content = "后一页 >>"; btnNext.HorizontalContentAlignment = HorizontalAlignment.Center; btnNext.VerticalContentAlignment = VerticalAlignment.Center; btnNext.Cursor = Cursors.Hand; Canvas.SetLeft(btnNext, 151); Canvas.SetTop(btnNext, 605); this.Children.Add(btnNext); //页码文本的设置 PageNum = new TextBlock(); PageNum.Width = 100; PageNum.Height = 20; PageNum.Text = "00 / 00"; PageNum.TextAlignment = TextAlignment.Right; PageNum.VerticalAlignment = VerticalAlignment.Center; PageNum.FontFamily = new FontFamily("Comic sans MS"); Canvas.SetLeft(PageNum, 340); Canvas.SetTop(PageNum, 607); this.Children.Add(PageNum); } //设置图片路径 public void setterimgPhoto(string path) { BitmapImage btm = new BitmapImage(); btm.UriSource = new Uri(path, UriKind.Relative); imgPhoto.Source = btm; } //设置按钮是否可见 public void setterDisplayBtnNext(bool YesNo) { if (YesNo) { btnNext.Visibility = Visibility.Visible; } else { btnNext.Visibility = Visibility.Collapsed; } } //设置页码 public void setterPageNumber(string currentPageNum, string TotalPageNum) { PageNum.Text = currentPageNum + " / " + TotalPageNum; } //返回按钮单击事件关联 public Button getbtnNext() { return btnNext; } } } 3、构建应用程序界面 详细的说明请见代码注释。 MainPage.xaml文件代码: CodeUserControl x:Class="SilverlightClient.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:SLMitsuControls;assembly=SLMitsuControls" mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480" Loaded="UserControl_Loaded"> <Grid x:Name="LayoutRoot"> <Canvas x:Name="layout" Background="White" Width="906" Height="630" Canvas.Left="0" Canvas.Top="0"> <!--显示层--> <Canvas x:Name="canvasBook" Background="White" Width="906" Height="630" Canvas.Left="0" Canvas.Top="0" Visibility="Collapsed"> <local:UCBook x:Name="book" Width="906" Height="630" Canvas.Left="0" Canvas.Top="0" /><!--BookControl--> </Canvas> <!--加载层--> <Canvas x:Name="canvChanging" Width="500" Height="75" Canvas.Left="200" Canvas.Top="250" Visibility="Collapsed" Background="Transparent"> <TextBlock x:Name="changingText" Text="页面加载中 " Width="200" Height="30" Canvas.Left="0" Canvas.Top="0" FontFamily="comic sans ms" FontSize="14"></TextBlock> <ProgressBar x:Name="changingProgressBar" Width="500" Height="30" Canvas.Left="0" Canvas.Top="30"></ProgressBar> </Canvas> </Canvas> </Grid> </UserControl> 4、设置应用程序控制逻辑 详细的说明请见代码注释。 1)MainPage.xaml.cs文件代码: Code System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Threading; using SLMitsuControls; namespace SilverlightClient { public partial class MainPage : UserControl, IDataProvider { //定义全局变量 private List<object> PageObjectList;//页面对象列表 public enum PageType { right, left };//页面类型 public string fileMedia = "";//文件媒体 public string headerPage = "";//首页 public int maxiPageNum = 0;//最大页数 public enum Location { local, web };//枚举应用程序所在 public Location modeLocation; private int pageDownload = 0;//下载的页面数 private string uriResources = "";//Uri地址 //构造函数 public MainPage() { InitializeComponent(); PageObjectList = new List<object>(); } //UserControl事件触发处理 private void UserControl_Loaded(object sender, RoutedEventArgs e) { if (modeLocation == Location.local) { this.canvChanging.Visibility = Visibility.Collapsed; this.canvasBook.Visibility = Visibility.Visible; //填充页面列表 FillPagesList(); } if (modeLocation == Location.web) { this.canvChanging.Visibility = Visibility.Visible; this.canvasBook.Visibility = Visibility.Collapsed; //开始下载页面 DownloadPages(); } } //开始将页面填充至List中 private void FillPagesList() { //用页面填充列表 for (int xx = 1; xx <= maxiPageNum; xx++) { if (xx % 2 != 0) { //前一页即奇数页 AddPageToList(PageType.right, fileMedia + "/" + headerPage + xx.ToString("00") + ".jpg", xx.ToString(), maxiPageNum.ToString(), true); } else { //后一页即偶数页 AddPageToList(PageType.left, fileMedia + "/" + headerPage + xx.ToString("00") + ".jpg", xx.ToString(), maxiPageNum.ToString(), true); } } //移除最后一页的按钮 TypePage.RightPage page = PageObjectList[maxiPageNum - 1] as TypePage.RightPage; page.setterDisplayBtnNext(false); //为翻页按钮指派事件触发处理 for (int xx = 1; xx < maxiPageNum; xx++) { if (xx % 2 != 0) { //前一页即奇数页 TypePage.RightPage pp = PageObjectList[xx - 1] as TypePage.RightPage; Button btnNext = pp.getbtnNext(); btnNext.Click += new RoutedEventHandler(btnNext_Click); } else { //后一页即偶数页 TypePage.LeftPage pp = PageObjectList[xx - 1] as TypePage.LeftPage; Button btnPrevious = pp.getbtnPrevious(); btnPrevious.Click += new RoutedEventHandler(btnPrevious_Click); } } //为Book设置数据内容 book.SetData(this); } //向页面列表中添加具体页面 private void AddPageToList(PageType pageType, string pathImage, string numPage, string numMaxiPage, bool showBtnYesNo) { switch (pageType) { case PageType.right: TypePage.RightPage pcd = new SilverlightClient.TypePage.RightPage(); pcd.setterimgPhoto(pathImage); pcd.setterPageNumber(numPage, numMaxiPage); pcd.setterDisplayBtnNext(showBtnYesNo); PageObjectList.Add(pcd); break; case PageType.left: TypePage.LeftPage pcg = new SilverlightClient.TypePage.LeftPage(); pcg.setterimgPhoto(pathImage); pcg.setterPageNumber(numPage, numMaxiPage); pcg.setterDisplayBtnPrevious(showBtnYesNo); PageObjectList.Add(pcg); break; } } //“下一页”按钮事件触发处理 private void btnNext_Click(object sender, RoutedEventArgs e) { book.AnimateToNextPage(500); } //“上一页”按钮事件触发处理 private void btnPrevious_Click(object sender, RoutedEventArgs e) { book.AnimateToPreviousPage(500); } //从网络上下载页面 private void DownloadPages() { this.canvChanging.Visibility = Visibility.Visible; this.uriResources = Application.Current.Host.Source.AbsoluteUri; int index = uriResources.IndexOf("SilverlightClient.xap"); uriResources = uriResources.Substring(0, index); this.changingProgressBar.Minimum = 0; this.changingProgressBar.Maximum = maxiPageNum - 1; string theResources = uriResources + fileMedia + "/" + headerPage + (pageDownload + 1).ToString("00") + ".jpg"; string theResourcesNum = headerPage + (pageDownload + 1).ToString("00") + ".jpg"; AsynchronouslyDownloadPage(theResources, theResourcesNum); } //异步下载页面 private void AsynchronouslyDownloadPage(string path, string num) { WebClient unWeb = new WebClient(); unWeb.DownloadStringCompleted += new DownloadStringCompletedEventHandler(unWeb_DownloadStringCompleted); unWeb.DownloadStringAsync(new Uri(path)); this.changingText.Text = "正在下载 : " + num; this.changingProgressBar.Value = this.pageDownload; } //异步下载页面完成事件触发处理 private void unWeb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { this.pageDownload++; if (this.pageDownload < this.maxiPageNum)//持续不断下载页面直到全部页面都下完 { string theResources = uriResources + fileMedia + "/" + headerPage + (pageDownload + 1).ToString("00") + ".jpg"; string theResourcesNum = headerPage + (pageDownload + 1).ToString("00") + ".jpg"; AsynchronouslyDownloadPage(theResources, theResourcesNum); } else { FillPagesList(); this.canvChanging.Visibility = Visibility.Collapsed; this.canvasBook.Visibility = Visibility.Visible; } } //强制声明接口 #region IDataProvider Members public object GetItem(int index) { return PageObjectList[index]; } public int GetCount() { return PageObjectList.Count; } #endregion } } 2)App.xaml.cs文件代码: Code System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace SilverlightClient { public partial class App : Application { public string gFileMedia = ""; public string gHeaderPage = ""; public int gPageNumber = 0; public string gModeLocation = ""; public App() { this.Startup += this.Application_Startup; this.Exit += this.Application_Exit; this.UnhandledException += this.Application_UnhandledException; InitializeComponent(); } private void Application_Startup(object sender, StartupEventArgs e) { int paramOk = 0; //从HTML中取出初始化数据 if (e.InitParams.ContainsKey("gFile")) { gFileMedia = e.InitParams["gFile"]; paramOk++; } if (e.InitParams.ContainsKey("gHeaderPage")) { gHeaderPage = e.InitParams["gHeaderPage"]; paramOk++; } if (e.InitParams.ContainsKey("gNum")) { string recup = e.InitParams["gNum"]; gPageNumber = int.Parse(recup); paramOk++; } if (e.InitParams.ContainsKey("gLocation")) { gModeLocation = e.InitParams["gLocation"]; paramOk++; } if (paramOk == 4) { //初始化MainPage MainPage maPage = new MainPage(); maPage.fileMedia = gFileMedia; maPage.headerPage = gHeaderPage; maPage.maxiPageNum = gPageNumber; if (gModeLocation.CompareTo("local") == 0) { maPage.modeLocation = MainPage.Location.local; } if (gModeLocation.CompareTo("web") == 0) { maPage.modeLocation = MainPage.Location.web; } this.RootVisual = maPage; } } private void Application_Exit(object sender, EventArgs e) { } private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (!System.Diagnostics.Debugger.IsAttached) { e.Handled = true; Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); }); } } private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e) { try { string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace; errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n"); System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");"); } catch (Exception) { } } } } 3)在SilverlightClientTestPage.aspx文件(位于工程FlipPage文件夹下)中,添加用绿色粗体标明的代码: <body> <form id="form1" runat="server" style="height:100%"> <div id="silverlightControlHost"> <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%"> <param name="source" value="ClientBin/SilverlightClient.xap"/> <param name="onError" value="onSilverlightError" /> <param name="background" value="white" /> <param name="minRuntimeVersion" value="3.0.40624.0" /> <param name="autoUpgrade" value="true" /> <!--设置Book初始化参数--> <param name="initParams" value="gFile=mediaPictures, gHeaderPage=albumPictures, gNum=9, gLocation=web" /> <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration:none"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/> </a> </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div> </form> </body> 5、最终效果图 [项目源文件下载]
代理IP的高匿名,匿名和透明的区别
若是从隐藏使用代理用户的级别上划分,代理能够分为三种,即高度匿名代理、普通匿名代理和透明代理。
(1)高度匿名代理不改变客户机的请求,这样在服务器看来就像有个真正的客户浏览器在访问它,这时客户的真实IP是隐藏的,服务器端不会认为咱们使用了代理。
(2)普通匿名代理能隐藏客户机的真实IP,但会改变咱们的请求信息,服务器端有可能会认为咱们使用了代理。不过使用此种代理时,虽然被访问的网站不能知道你的ip地址,但仍然能够知道你在使用代理,固然某些可以侦测ip的网页仍然能够查到你的ip。
(3)透明代理,它不但改变了咱们的请求信息,还会传送真实的IP地址。
三者隐藏使用代理者身份的级别依次为高度匿名代理最隐蔽,其次是普通匿名代理,最差的是透明代理。
对winform中tabContorl隐藏tabPage的补充
前几天说到winfom中tabContorl隐藏tabPage的问题,总的来讲达到了目的,但效果通常。 今天在看msdn时候发现了一个tabPage的属性其实也能够实现这个效果。 微软对tabContorl中的tabPage隐藏的实现方法也是在集合中删除,彷佛只有这一个方法,因此个人方法也跟这个差很少。 就是设置tabPage的parent属性为null 原理很简单,若是tabPage的parent控件不存在,则tabPage也不存在。 若是想让它显示就设置tabPage的parent为tabContorl控件就能够了。 下面是主要代码 /// <summary> /// 隐藏tabPage1 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load(object sender, EventArgs e) { this.tabPage1.Parent = null; } /// <summary> /// 显示tabPage1 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { this.tabPage1.Parent = this.tabControl1; } 很简单吧? 恩,不过问题跟上一次同样,顺序又不对了。 但这个问题只存在于隐藏了前一个tabPage的状况。
分解Gif图像
对于一个Gif进行拆分,其实Image对象自己就支持,例如对于一个Gif文件拆分红Jpeg文件方式,能够按照以下的方式进行处理。 using System.Drawing.Drawing2D; using System.Drawing.Imaging; Image imgGif = Image.FromFile(@"d:\test.gif"); //Create a new FrameDimension object from this image FrameDimension ImgFrmDim = new FrameDimension( imgGif.FrameDimensionsList[0] ); //Determine the number of frames in the image //Note that all images contain at least 1 frame, //but an animated GIF will contain more than 1 frame. int nFrameCount = imgGif.GetFrameCount( ImgFrmDim ); // Save every frame into jpeg format for( int i = 0; i < nFrameCount; i++ ) { imgGif.SelectActiveFrame( ImgFrmDim, i ); imgGif.Save( string.Format( @"d:\Frame{0}.jpg", i ), ImageFormat.Jpeg ); }