RichTextBox 文件拖动

           其实很早就想写了,也没什么技术含量,就是因为没有写过。觉得自己不会写,所以就写着试试。

           做的是自定义控件,还是贴代码吧。

           功能:设置可以拖拽的文件类型,将文本异步显示到RichTextBox。

1 using System;
2  using System.Collections.Generic;
3 using System.Text;
4 using System.Windows.Forms;
5 using System.ComponentModel;
6
7 class gxRichTextBox:System.Windows.Forms.RichTextBox
8 {
9
10 private delegate void ReadFileOneByOne(string FilePath);
11 public gxRichTextBox()
12 {
13 this.AllowDrop = true;//接受拖拽
14 this.AcceptsTab = true;//接受TAB键
15 this.DragDrop += new System.Windows.Forms.DragEventHandler(gxRichTextBox_DragDrop);
16 this.DragEnter += new System.Windows.Forms.DragEventHandler(gxRichTextBox_DragEnter);
17 }
18
19 private string _gxFilter = "txt,sql,asm";
20 [Description("可以打开的文件类型,以 ,分割开")]
21 public string GxFilter
22 {
23 get { return _gxFilter; }
24 set { _gxFilter = value; }
25 }
26
27 void gxRichTextBox_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
28 {
29 if (e.Data.GetDataPresent(DataFormats.FileDrop))
30 {
31 e.Effect = DragDropEffects.Copy;
32 }
33 else
34 {
35 e.Effect = DragDropEffects.None;
36 }
37 }
38
39 void gxRichTextBox_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
40 {
41 string filepath = ((string[])e.Data.GetData(DataFormats.FileDrop))[0].ToString();
42 ReadFileOneByOne rf = new ReadFileOneByOne(ReadFile);
43 rf.BeginInvoke(filepath, null, null);
44 }
45
46 void ReadFile(string filepath)
47 {
48 byte[] buffer = new byte[1024 * 8];//每次读取多少
49 long f_len = 0; //文件流的当前位置
50 string fileExt = System.IO.Path.GetExtension(filepath).ToUpper();//文件类型
51 foreach (string str in _gxFilter.ToUpper().Split(','))
52 {
53 if (fileExt == "."+str)
54 {
55 System.IO.FileStream fl = null;
56 try
57 {
58 fl = new System.IO.FileStream(filepath, System.IO.FileMode.Open);
59 }
60 catch (Exception ex)
61 {
62 MessageBox.Show(ex.Message);
63 }
64 this.Text = string.Empty;
65 int effect = 0;//校验文件是否读取完毕的状态
66 do
67 {
68 effect = fl.Read(buffer, 0, buffer.Length);//循环读取文件
69 f_len += effect; //累加校验和
70 this.AppendText(Encoding.Default.GetString(buffer));//边读边显示
71 fl.Seek(f_len, System.IO.SeekOrigin.Begin);//设置读取指针的当前位置
72 } while (effect == buffer.Length);
73 byte[] lastbuffer = new byte[fl.Length % buffer.Length];
74 fl.Read(lastbuffer, 0, lastbuffer.Length); //截取最后没有读取的部分
75 if (fl.Length != f_len)
76 {
77 MessageBox.Show("文件数据丢失!");
78 }
79 this.AppendText(Encoding.Default.GetString(lastbuffer));//显示最后一部分
80 fl.Close();
81 fl.Dispose();
82 }
83 }
84
85 }
86 }
87
88

关键地方都有注释,我就不多说了。

posted @ 2011-01-27 17:35  莫问哥哥  阅读(799)  评论(2编辑  收藏  举报