【发布时间】:2013-11-18 16:23:13
【问题描述】:
我正在为一个项目开发系统托盘应用程序。当我点击“切换开启”时,我目前卡住了,它不会自行变为“切换关闭”,我希望也许有人能告诉我我做错了什么并帮助我修复它。
上下文菜单的代码
using System;
using System.Diagnostics;
using System.Windows.Forms;
using TestApplicationforRIVC.Properties;
using System.Drawing;
namespace TestApplicationforRIVC {
class RIVCContextMenu {
//Is Add Box Displayed?
bool isAddLoaded = false;
//Is the Clear box Displayed?
bool isClearLoaded = false;
//Is it listening for voice?
bool toggleOn = false;
//Creates this Instance
public ContextMenuStrip Create() {
//Add the Default Menu Options
ContextMenuStrip menu = new ContextMenuStrip();
ToolStripMenuItem item;
ToolStripMenuItem off;
ToolStripSeparator sep;
if(toggleOn) {
//Toggle Off
item = new ToolStripMenuItem();
item.Text = "Toggle Off";
item.Click += new EventHandler(toggleOffClick);
item.Image = Resources.toggleOff;
menu.Items.Add(item);
}
if(!toggleOn) {
//Toggle On
item = new ToolStripMenuItem();
item.Text = "Toggle On";
item.Click += new EventHandler(toggleOnClick);
item.Image = Resources.toggleOn;
menu.Items.Add(item);
}
// Separator.
sep = new ToolStripSeparator();
menu.Items.Add(sep);
//Add to RIVC Library
item = new ToolStripMenuItem();
item.Text = "Add to Library";
item.Click += new EventHandler(addClick);
item.Image = Resources.Add;
menu.Items.Add(item);
//Clear RIVC Library
item = new ToolStripMenuItem();
item.Text = "Clear Library";
item.Click += new EventHandler(clearClick);
item.Image = Resources.Delete;
menu.Items.Add(item);
// Separator.
sep = new ToolStripSeparator();
menu.Items.Add(sep);
//Exit Program
item = new ToolStripMenuItem();
item.Text = "Exit";
item.Click += new System.EventHandler(exitClick);
item.Image = Resources.Exit;
menu.Items.Add(item);
return menu;
}
//Handles the Click Event of the Toggle On Control
void toggleOnClick(object sender, EventArgs e) {
toggleOn = true;
}
//Handles the Click Even of the Toggle Off Control
void toggleOffClick(object sender, EventArgs e) {
toggleOn = false;
}
//Handles the Click Event of the Add Control
void addClick(object sender, EventArgs e) {
if(!isAddLoaded) {
isAddLoaded = true;
//enter Dialog Box Info
isAddLoaded = false;
}
}
//Handles the Click Event of the Clear Control
void clearClick(object sender, EventArgs e) {
if(!isClearLoaded) {
isClearLoaded = true;
//enter dialog box info
isClearLoaded = false;
}
}
//Handles the Click Event of the Exit Control
void exitClick(object sender, EventArgs e) {
Application.Exit();
}
}
}
希望你们能帮我解决这个小错误。
【问题讨论】:
-
为什么每次都创建一个全新的菜单?为什么不直接在 Click 处理程序中更改 ToolStripMenuItem() 的 .Text() 属性?
-
当您点击“Toggle On”时,您只需将“toggleOn”字段更改为“true”。您是否创建了 ContextMenuStrip 的新实例?我建议您按照@Idle_Mind 的建议做并更改文本,然后您可以使用单个处理程序来更改“toggleOn”。