2008年9月16日星期二

C#程序开发 章一

手头有一本书《C#程序开发范例宝典》。
大概是相当出色的书,因为例子很多。

只可惜源码是基于vs2005写的,所以在vs2008运行就有很多错误。
我将在学习过程中,把正确的步骤和源码记下来,供大家参考。

实例001 带历史信息的菜单

操作步骤:
(1)新建 Windows窗体应用程序 项目,命名为 Ex01_01,默认窗体为 Form1。
(2)从工具箱添加 MenuStrip 和 OpenFileDialog 控件。

完整代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace HistoryMenu
{
public partial class Form1 : Form
{
string address;
public Form1()
{
InitializeComponent();
address = System.Environment.CurrentDirectory;
}

private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.FileName = "";
this.openFileDialog1.ShowDialog();
StreamWriter s = new StreamWriter(address + "\\Menu.ini", true);
s.WriteLine(openFileDialog1.FileName); //写入ini文件
s.Flush();
s.Close();
ShowWindows(openFileDialog1.FileName);
}

private void Form1_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(address + "\\Menu.ini");
int i = this.文件ToolStripMenuItem.DropDownItems.Count - 2;
while (sr.Peek() >= 0)//读取ini文件
{
ToolStripMenuItem menuitem = new ToolStripMenuItem(sr.ReadLine());
this.文件ToolStripMenuItem.DropDownItems.Insert(i, menuitem);
i++;
menuitem.Click += new EventHandler(menuitem_Click);
}
}

private void menuitem_Click(object sender, EventArgs e)
{
ToolStripMenuItem menu = (ToolStripMenuItem)sender;
ShowWindows(menu.Text);
}

public void ShowWindows(string filename)
{
Image p = Image.FromFile(filename);
Form f = new Form();
f.MdiParent = this;
f.BackgroundImage = p;
f.Show();
}
}
}

没有评论: