2014-10-27 67 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