在显示之前查找 ContextMenuStrip 的高度
我有一个 ContextMenuStrip (ctMenuMassEdit),我想在左键单击按钮 (btnMassEdit) 时显示它。我希望 ContextMenuStrip 显示在按钮上方,即相对于按钮的位置 (0,-ContextMenuStrip.Height):
private void btnMassEdit_Click(object sender, EventArgs e)
{
ctMenuMassEdit.Show(btnMassEdit, new Point(0, -ctMenuMassEdit.Height));
}
但是,第一次单击按钮时 Height 属性为 0 (我假设之前没有创建 ContextMenuStrip第一次显示),结果是 ContextMenuStrip 出现在按钮的顶部。然而,当我第二次单击该按钮时,它出现在正确的位置,因此我的基本逻辑至少是正确的。
我尝试在显示 ContextMenuStrip 之前添加以下内容,但它没有按预期工作:
if (!ctMenuMassEdit.Created)
{
ctMenuMassEdit.CreateControl();
}
那么,有没有一种方法可以在第一次显示之前创建 ContextMenuStrip,以便我拥有正确的 Height 属性?我当然可以使用显示它、隐藏它并再次显示它的技巧,但这看起来不太整洁......
I have a ContextMenuStrip (ctMenuMassEdit) that I want to display when left-clicking a button (btnMassEdit). I want the ContextMenuStrip to be displayed above the button, i.e. position (0,-ContextMenuStrip.Height) relative to the button:
private void btnMassEdit_Click(object sender, EventArgs e)
{
ctMenuMassEdit.Show(btnMassEdit, new Point(0, -ctMenuMassEdit.Height));
}
However, the Height property is 0 the first time the button is clicked (I assume the ContextMenuStrip isn't created before it is shown the first time), and the result is that the ContextMenuStrip appears on top of the button. The 2nd time I click the button however, it appears in the correct position, so the basic of my logic is at least correct.
I tried adding the following before showing the ContextMenuStrip, but it didn't work as hoped:
if (!ctMenuMassEdit.Created)
{
ctMenuMassEdit.CreateControl();
}
So, is there a way I can create the ContextMenuStrip before showing it the first time, so I have the correct Height property? I could of course use the hack of showing it, hiding it and showing it again, but that doesn't seem really neat...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样
ctMenuMassEdit.Show(btnMassEdit, Me.PointToScreen(btnMassEdit.Location),ToolStripDropDownDirection.AboveRight);
how about
ctMenuMassEdit.Show(btnMassEdit, Me.PointToScreen(btnMassEdit.Location),ToolStripDropDownDirection.AboveRight);
由于没有其他人有任何建议,我只能分享我的解决方案。这并不是一个真正的解决方案,更像是一个黑客,但如果我隐藏它并第一次再次显示它,它会起作用:
你可能想知道为什么我检查 Height < 5 而不是简单的 Height == 0?好吧,出于某种奇怪的原因,在我第一次显示 ContextMenuStrip 之前,它的高度似乎为 4(而不是人们想象的 0),所以这是 hack 中的另一个 hack ;)
Since nobody else had any suggestions, I can just share what ended to be my solution. It's not really a solution, more a hack, but if I hide it and show it again the first time, it works:
You might wonder why I check Height < 5 and not simply Height == 0? Well, for some strange reason, the ContextMenuStrip seemed to have a height of 4 before I displayed it the first time (not 0, as one would assume), so it's yet another hack inside the hack ;)