[英]How to put a ContextMenu into the header of a TabPage
我有一個自定義TabControl
,其中我有TabPages
與ContextMenu
綁定到它們。
我希望菜單僅在單擊頁眉時顯示。
我所做的是,當單擊TabControl
時,我檢查以下條件:
private void MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == Mousebuttons.Right)
{
for (int i = 0; i < TabCount; ++i)
{
Rectangle r = GetTabRect(i);
if (r.Contains(e.Location) /* && it is the header that was clicked*/)
{
// Change slected index, get the page, create contextual menu
ContextMenu cm = new ContextMenu();
// Add several items to menu
page.ContextMenu = cm;
page.ContextMenu.Show(this, e.Location);
}
}
}
}
如果我將MouseUp
綁定到TabControl
,我會在整個TabPage
獲取ContextMenu
。 如果我將它綁定到TabPage
,我只在正文中獲取ContextMenu
而不在標題中。
有沒有辦法讓ContextMenu只顯示在標題點擊?
只是不要將ContextMenu分配給任何東西......只需顯示它:
public class MyTabControl : TabControl
{
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
for (int i = 0; i < TabCount; ++i)
{
Rectangle r = GetTabRect(i);
if (r.Contains(e.Location) /* && it is the header that was clicked*/)
{
// Change slected index, get the page, create contextual menu
ContextMenu cm = new ContextMenu();
// Add several items to menu
cm.MenuItems.Add("hello");
cm.MenuItems.Add("world!");
cm.Show(this, e.Location);
break;
}
}
}
base.OnMouseUp(e);
}
}
而不是像Idle_Mind所說的那樣覆蓋,你也可以對mouseevent上的普通tabcontrol做同樣的事情:
private void tabControl1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
for (int i = 0; i < tabControl1.TabCount; ++i)
{
Rectangle r = tabControl1.GetTabRect(i);
if (r.Contains(e.Location) /* && it is the header that was clicked*/)
{
// Change slected index, get the page, create contextual menu
ContextMenu cm = new ContextMenu();
// Add several items to menu
cm.MenuItems.Add("hello");
cm.MenuItems.Add("world!");
cm.Show(tabControl1, e.Location);
break;
}
}
}
}
它完全相同,但不會在工具箱中添加額外的控件:)如果要在多個TabControl上使用它,也可以使它成為通用的。
private void showContextMenu_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
TabControl tabControl1 = sender as TabControl;
[...]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.