c# - 防止 ToolStripMenuItems 跳转到第二个屏幕

标签 c# winforms multiple-monitors notifyicon toolstripdropdown

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

enter image description here

我怎样才能强制他们保持在同一个屏幕上?我尝试通过网络进行搜索,但找不到合适的答案。

这是我用来测试这个 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);
    }
}

最佳答案

这并不容易,但您可以在 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;
    }
}

此外,请确保您拥有 DropDownOpening事件连接(你真的需要将它添加到每个菜单项):

level1ToolStripMenuItem += submenu_DropDownOpening;

关于c# - 防止 ToolStripMenuItems 跳转到第二个屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26587843/

相关文章:

windows - 如何在命令行中从重复显示切换到多个显示器

C# 辅助监视器边界问题

c# - 当 POST 回我的 Controller 时,我是否必须将部分 View 的数据重新分配回模型?

c# - 使用 C# 版本的 Quicktime 读取时间码轨道数据

c# - 在 WinForms 中绑定(bind)到 WPF 托管控件的 DependencyProperty

C# Mysql datareader - 如何使用 datareader 获取其他列

c# - 有没有办法在 WCF 中实现核心代码模板?

c# - 为什么我的测试项目没有出现在测试资源管理器中

c# - 如何动态填充 CheckedListBox?

multiple-monitors - Gnome-shell wayland,旋转屏幕