丽水市汽车运输集团有限公司信息中心 苟安廷
VS2005比VS2003有了很大的改进,尤其是程序主菜单,一改原来单调的模式,变成XP风格了,在C#2003中,主菜单用的是MainMenu类,在C#2005中,改为MenuStrip类,当然,为了保持兼容,仍然可以用原来的MainMenu类,在对原来的项目进行升级时,并不会将主菜单的MainMenu类自动更改为MenuStrip类,当然,此时你可以将原来的主菜单删除,重新添加一个MenuStrip的主菜单,不过,这对于一个有大量菜单项的主菜单,工作量是很大的,且容易出错,我们按照下面的步骤进行替换操作:
1、 切换到主菜单定义的文件中和实现的文件中。
2、 选择系统控件定义(也就是private System.Windows.Forms.MenuItem menuItem1;等这一部分)部分和实现部分(也就是#region 设计器生成的代码所折叠的区域)。
3、 按Ctrl+H弹出替换对话框,为防止误替换,替换范围为选择的部分,并勾选“搜索隐藏文本” 项。
4、 将private System.Windows.Forms.MainMenu替换为
private System.Windows.Forms.MenuStrip
5、 将private System.Windows.Forms.MenuItem替换为:
private System.Windows.Forms.ToolStripMenuItem
6、 将new System.Windows.Forms.MainMenu(this.components) 替换为:
new System.Windows.Forms.MenuStrip()
7、 将new System.Windows.Forms.MenuItem()替换为:
new System.Windows.Forms.ToolStripMenuItem()
8、 将MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {替换为:
Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
9、 将System.Windows.Forms.Shortcut {替换为:
System.Windows.Forms.Keys,该操作是替换快捷键。
10、 由于MenuStrip和MenuStrip的快捷键指定方式不一样,因此,将Shortcut =替换成ShortcutKeys =
11、 最后,将this.Menu = this.mainMenu1;(mainMenu1为VS2003中添加的主菜单名称)改为:this.MainMenuStrip = this.mainMenu1;并加上一句
this.Controls.Add(mainMenu1);
编译一下,根据报错信息,删除原MenuStrip类中为子菜单指定Index属性的行,并将顶级菜单添加子菜单的项手工由ITems修改为DropDownItems,如:
this.menuItem5.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
改为
this.menuItem5.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
通过上面的操作就可以完成菜单的升级,因为都是通过复制/粘贴完成的,虽然步骤看起来较多,操作并不麻烦,为了使用程序支持XP风格,别忘了在原来的
[STAThread]
static void Main()
{
Application.Run(new frmMain());
}
中增加两句,改为:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}