【问题标题】:Who is displaying the ContextMenu: the form or the notification icon?谁在显示 ContextMenu:表单还是通知图标?
【发布时间】:2021-01-29 13:34:05
【问题描述】:

我将相同的ContextMenu 分配给了一个表单和一个 NotifyIcon。

this.ContextMenu = this.contextMenu;
this.notifyIcon.ContextMenu = this.ContextMenu;

在上下文菜单的Popup 事件中,我试图找出谁在显示上下文菜单:表单(例如右键单击表单)或通知图标(右键单击通知图标):

private void ContextMenu_Popup(object sender, EventArgs e) 
{
    System.Diagnostics.Debug.WriteLine(this.contextMenu.SourceControl.Name);
}

但是,我总是将表单作为源代码控制,即使我右键单击通知图标。

我正在使用 C#、.NET Framework 4.6 和 Windows 窗体。

【问题讨论】:

  • 您可以查看sender 对象。在我的测试项目中,当我右键单击表单时,它的SourceControl 是我的表单,当我右键单击通知图标时,它是null

标签: c# .net winforms contextmenu notifyicon


【解决方案1】:

也许,最快的方法是有一个标志:

private bool fromIcon;

private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
{
   if (e.Button == MouseButtons.Right)
   {
      fromIcon = true;
   }
}

private void ContextMenu_Popup(object sender, EventArgs e) 
{
    System.Diagnostics.Debug.WriteLine(fromIcon.ToString());
    fromIcon = false;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    相关资源
    最近更新 更多