我有一个主要通过 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);
}
}
最佳答案
这并不容易,但您可以在 DropDownOpening
中编写代码查看菜单所在位置(边界)、当前屏幕的事件,然后设置 DropDownDirection
的 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;
}
}
此外,请确保您拥有 DropDownOpening
事件连接(你真的需要将它添加到每个菜单项):
level1ToolStripMenuItem += submenu_DropDownOpening;
关于c# - 防止 ToolStripMenuItems 跳转到第二个屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26587843/