简体   繁体   English

C# 当托盘图标不在同一个表单上时,如何将上下文菜单分配给托盘图标?

[英]C# How can I assign a context menu to a tray icon when the tray icon is not on the same form?

I used the code below to programmatically create a system tray icon, this code lives in class file and not on my main form.我使用下面的代码以编程方式创建系统托盘图标,此代码位于 class 文件中,而不是我的主窗体中。 I have dragged a contextMenuStrip control on to my main form, I now need to link the two but as the control if private I can't see it.我已将 contextMenuStrip 控件拖到我的主窗体上,现在我需要将两者链接起来,但如果是私有的控件,我看不到它。 What is the best way to link these two?将这两者联系起来的最佳方式是什么?

trayIcon = new NotifyIcon();
trayIcon.Icon = mainForm.Icon;
trayIcon.Text = "Test";
trayIcon.MouseDoubleClick += new MouseEventHandler(this.trayIcon_MouseDoubleClick);
trayIcon.ContextMenuStrip = //help needed here???

Thanks all谢谢大家

You can set the Modifiers property of the contextMenuStrip to public.您可以将 contextMenuStrip 的 Modifiers 属性设置为 public。

Nothing to stop you making the contextMenuStrip on the main form public, apart from the sheer nastiness of it.没有什么能阻止你将主窗体上的 contextMenuStrip 公开,除了它的纯粹肮脏。

If you're worried about making the actual ContextMenuStrip field public, why not instead provide a non-private read only field.如果您担心公开实际的 ContextMenuStrip 字段,为什么不提供一个非私有只读字段。 This will still maintain a level of encapsulation in your main form object.这仍将在您的主窗体 object 中保持一定程度的封装。

public class MainForm { ...
  public ContextmenuStrip MyMenuStrip { 
    get { return contextMenuStrip; }
  }
}

Then you could just access mainForm.MyMenuStrip for the tray icon.然后您可以访问 mainForm.MyMenuStrip 以获取托盘图标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM