防止 ToolStripMenuItems 跳转到第二个屏幕

atl*_*teh 5 c# multiple-monitors notifyicon winforms toolstripdropdown

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

在此处输入图片说明

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

这是我用来测试这个 senario 的一段示例代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 5

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,请确保您已连接DropDownOpening事件(您确实需要将其添加到每个菜单项中):

level1ToolStripMenuItem += submenu_DropDownOpening;
Run Code Online (Sandbox Code Playgroud)