2014-10-27 68 views
1

我有一个应用程序,主要通过NotifyIcon的ContextMenuStrip操作
有多个级别的ToolStripMenuItems,用户可以通过它们。
问题是,当用户有两个屏幕时,MenuItems在没有可用空间时跳转到第二个屏幕。像这样:防止ToolStripMenuItems跳转到第二个屏幕

enter image description here

我怎么能强迫他们留在同一屏幕上?我试图通过网络搜索,但找不到合适的答案。

这里是一个代码示例一块我使用来测试这个塞纳里奥:

public partial class Form1 : Form 
{ 

    public Form1() 
    { 
     InitializeComponent(); 

     var resources = new ComponentResourceManager(typeof(Form1)); 
     var notifyIcon1 = new NotifyIcon(components); 
     var contextMenuStrip1 = new ContextMenuStrip(components); 
     var level1ToolStripMenuItem = new ToolStripMenuItem("level 1 drop down"); 
     var level2ToolStripMenuItem = new ToolStripMenuItem("level 2 drop down"); 
     var level3ToolStripMenuItem = new ToolStripMenuItem("level 3 drop down"); 

     notifyIcon1.ContextMenuStrip = contextMenuStrip1; 
     notifyIcon1.Icon = ((Icon)(resources.GetObject("notifyIcon1.Icon"))); 
     notifyIcon1.Visible = true; 

     level2ToolStripMenuItem.DropDownItems.Add(level3ToolStripMenuItem); 
     level1ToolStripMenuItem.DropDownItems.Add(level2ToolStripMenuItem); 
     contextMenuStrip1.Items.Add(level1ToolStripMenuItem); 
    } 
} 
+0

尝试使用表单设计器添加它并查看生成的代码。也许你只是错过了一项任务。行为看起来很奇怪,就像“等级3下拉”不能确定父母(坚持与父母相同的屏幕)。 – Sinatr 2014-10-27 13:04:39

+0

这是表单设计师。为了便于阅读,我对它进行了一些修改。 (将字段转换为当地人,并删除不必要的行) – atlanteh 2014-10-27 13:32:27

+0

Winforms中有特定的代码应该防止这种情况发生。它确实看起来有点古怪,请确认它是否在第二次*时打开上下文菜单。如果没有,我可以发布解决方法。 – 2014-10-27 13:42:39

回答

3

这是不容易的,但你可以在DropDownOpening事件编写代码,看看那里的菜单是(其边界),当前屏幕,然后设置ToolStripMenuItem

private void submenu_DropDownOpening(object sender, EventArgs e) 
    { 
     ToolStripMenuItem menuItem = sender as ToolStripMenuItem; 
     if (menuItem.HasDropDownItems == false) 
     { 
      return; // not a drop down item 
     } 

     // Current bounds of the current monitor 
     Rectangle Bounds = MenuItem.GetCurrentParent().Bounds; 
     Screen CurrentScreen = Screen.FromPoint(Bounds.Location); 

     // Look how big our children are: 
     int MaxWidth = 0; 
     foreach (ToolStripMenuItem subitem in menuItem.DropDownItems) 
     { 
      MaxWidth = Math.Max(subitem.Width, MaxWidth); 
     } 
     MaxWidth += 10; // Add a little wiggle room 

     int FarRight = Bounds.Right + MaxWidth; 

     int CurrentMonitorRight = CurrentScreen.Bounds.Right; 

     if (FarRight > CurrentMonitorRight) 
     { 
      menuItem.DropDownDirection = ToolStripDropDownDirection.Left; 
     } 
     else 
     { 
      menuItem.DropDownDirection = ToolStripDropDownDirection.Right; 
     } 
    } 

同样的DropDownDirection,请确保您有DropDownOpening事件挂钩(你真的需要把它添加到每个菜单项):

level1ToolStripMenuItem += submenu_DropDownOpening; 
+0

Thx男人!我早已忘记了这个应用程序,但现在我会尝试它:) – atlanteh 2015-11-15 16:42:08