【发布时间】:2014-08-07 06:57:09
【问题描述】:
我正在开发一个 C# WinForms 应用程序,其中有许多进程都由“主”应用程序管理。
在这个主应用程序中,每个进程都由其自己的FlowLayoutPanel 可视化,其中包含许多用于各种功能的按钮。我将这些面板称为“流程块”。
但是,当制作了许多这些过程时,并不是所有的块都可以轻松地显示在屏幕上。出于这个原因,我正在实施一个“紧凑模式”,它隐藏了所有进程块的所有按钮,只留下它们的名称、它们的状态和启动/停止按钮可见。然后我为每个进程块分配一个ContextMenuStrip,在其中我显示所有列为ToolStripMenuItem 的按钮,这样我就可以通过这种方式访问进程块的所有功能。我正在动态清除这些ContextMenuStrips 并在打开菜单时添加项目。
我通过遍历FlowLayoutPanel 的所有子控件来做到这一点,看看它们是否属于Button 类型,如果是,我将它们添加到ContextMenuStrip。见下面的代码sn-p:
private void PanelCmsOpened(object sender, EventArgs e) {
try {
ContextMenuStrip cMenuStrip = (ContextMenuStrip) sender;
// Clear all items from the context menu
cMenuStrip.Items.Clear();
// Loop over all controls in the FlowLayoutPanel
foreach (var c in CPanel.Controls) {
Button btn = c as Button;
if (btn == null) continue; // Not a button, continue
// Get the text from the button
string lbl = btn.Text;
if (string.IsNullOrEmpty(lbl)) {
try {
// The button has no text (only an icon), so we get the tooltip text of the button
lbl = PanelTooltip.GetToolTip(btn);
}
catch {
// We can't get any text to display, so skip this button
continue;
}
}
// Add a new item to the ContextMenuStrip
cMenuStrip.Items.Add(new ToolStripMenuItem(lbl,
btn.BackgroundImage,
(s, ea) => btn.PerformClick() // Perform a click on the button
)
{
Enabled = btn.Enabled
});
}
}
catch (Exception Ex) {
MessageBox.Show("Fout bij openen van context menu: " + Ex.Message, "Fout", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
问题:
现在一切正常,只要按钮可见。但是,当进入紧凑模式时,我通过设置它们的 Button.Visible 属性来隐藏按钮。在这种情况下,什么都不会发生。我尝试在PerformClick 周围放置一个try-catch 块,但没有抛出异常。只是什么都没有发生。有谁知道如何使隐藏按钮工作?
【问题讨论】:
标签: c# winforms button contextmenu