程序描述:简单的winform程序,实现简单的文本文件读写及相应鼠标事件
语言:C#
关键知识点:fileInfo/fileStream/streamReader/streamWrite/MousedownEvent/Exception/ArrayList/HashTable等
程序截图:
程序具体实现步骤:
- 先添加一个RichTextBox控件和三个Button控件,如图。
- save按钮实现对文本的存储,代码如下:
private void btnSaveFile_Click( object sender, EventArgs e)
... {
FileContent = this.txtContent.Text.ToString();
FileInfo fi = new FileInfo(FileName);
if (!fi.Exists)
...{
MessageBox.Show("File doesn't exist!Will be create! ");
}
FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(FileContent);
sw.Close();
fs.Close();
}
- read按钮实现对文本文件的读取,代码如下:
private void btnloadFile_Click( object sender, EventArgs e)
... {
FileInfo fi = new FileInfo(FileName);
if (!fi.Exists)
...{
MessageBox.Show("File doesn't exist!Will be create! ");
}
FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs);
txtContent.Text = sr.ReadToEnd();
sr.Close();
fs.Close();
}
- exception按钮用于抛出一个自定义异常,代码如下:
private void btnException_Click( object sender, EventArgs e)
... {
throw new Exception("I throw a new exception,but i don't know what's to do,hehe");
}
- 另外,为了随时获取RichTextBox中变化的文本,故为textchange事件添加代码如下:
private void txtContent_TextChanged( object sender, EventArgs e)
... {
this.FileContent = this.txtContent.Text;
}
- 另外,程序还实现了对窗口鼠标事件的响应:点击鼠标左键实现用ArrayList读取和存储每个单词,点击鼠标右键实现用HashTable存储每个单词并编号,点击鼠标中间实现显示程序作者信息,代码如下:
private void Form1_MouseDown( object sender, MouseEventArgs e)
... {
//LeftDown
if (e.Button == MouseButtons.Left)
...{
System.Collections.ArrayList listContent = new System.Collections.ArrayList();
string[] strContent = FileContent.Split(null);
foreach (string str in strContent)
...{
if (str != "")
...{
listContent.Add(str);
}
}
string strDisplay="";
foreach (object obj in listContent)
...{
string str = obj.ToString();
if (str != null)
...{
strDisplay += str;
strDisplay += System.Environment.NewLine;
}
}
MessageBox.Show(strDisplay);
}
//RightDown
if (e.Button == MouseButtons.Right)
...{
System.Collections.Hashtable ht = new System.Collections.Hashtable();
int number = 1;
string[] strContent = FileContent.Split(null);
foreach (string str in strContent)
...{
if (str != "")
...{
ht.Add(number,str);
number++;
}
}
string strDisplay="";
System.Collections.IDictionaryEnumerator enumer = ht.GetEnumerator();
while(enumer.MoveNext())
...{
strDisplay += enumer.Key.ToString()+":";
strDisplay += enumer.Value.ToString();
strDisplay += System.Environment.NewLine;
}
MessageBox.Show(strDisplay);
}
//MiddleDown show AuthorInformation
if (e.Button == MouseButtons.Middle)
...{
MessageBox.Show("Demo Author:Yanchao Website:www.yanchao.net.cn Email:yanchao.net.cn@gmail.com","About");
}
}
-
鼠标时间相应程序截图如下:
至此整个小程序完成,完整源代码:http://dl2.csdn.net/down4/20070715/15163704955.rar