更改选项卡控件中特定位置的颜色

时间:2013-09-20 12:24:03

标签: c# winforms tabcontrol

我有一个tab-controlDrawMode设置为OwnerDrawFixed。我希望当鼠标移动到tab-control中的特定位置时,应该更改位置的颜色。我尝试过使用Rectangle,但我仍然坚持如何更改Rectangle的颜色。

这就是我所拥有的。

    private void tabControl1_MouseMove(object sender, MouseEventArgs e)
    {
        for (int i = 0; i < this.tabControl1.TabPages.Count; i++)
        {
            Rectangle r = tabControl1.GetTabRect(i);
            Rectangle closeButton = new Rectangle(r.Right - 15, r.Top + 4, 12, 12);
            if (closeButton.Contains(e.Location))
            {
            }
        }
    }

编辑: DrawItem代码

    private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
    {
        e.Graphics.DrawString("x", e.Font, Brushes.Red, e.Bounds.Right-16, e.Bounds.Top+4);
        e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text, e.Font, Brushes.Black, e.Bounds.Left + 12, e.Bounds.Top + 4);
        e.DrawFocusRectangle();
    }

我的问题是,如何为矩形着色,如果不可能,我可以使用其他什么方式?。

2 个答案:

答案 0 :(得分:0)

首先GetTabRect没有按照你的想法做到。它获取控件的边界矩形,该矩形是完全包围控件的矩形的大小。这不是具有颜色等的“控件”,而是TabControl的属性。

由于我已经理解了你的问题,你在标签上有很多控件,你想在鼠标悬停时突出显示其中一些?

如果是这样,最简单的方法是使用容器控件(FlowLayoutPanelPanelSplitContainerTableLayoutPanel)并将控件放在其中。

我在选项卡上创建了一个带有选项卡控件和面板控件的基本表单。当鼠标进入或离开面板控制边时,以下代码会更改背景颜色。如果您不想,则无需在代码中连接MouseEnterMouseLeave事件......设计人员将向您显示哪些控件具有这些事件并将其连接到{ {1}}代码。

InitializeComponent()

如果我误解了你想突出显示实际的 public Form1() { InitializeComponent(); panel1.MouseEnter += new EventHandler(panel1_MouseEnter); panel1.MouseLeave += new EventHandler(panel1_MouseLeave); } void panel1_MouseLeave(object sender, EventArgs e) { panel1.BackColor = Color.Red; } void panel1_MouseEnter(object sender, EventArgs e) { panel1.BackColor = Color.PaleGoldenrod; } 那么,因为这个控件根本没有任何颜色属性,你需要将TabControl放在另一个控件中(比如Panel),或者建议在表单上手动绘制(在OnPaint事件中)。我不推荐这条路线,因为它可能变得非常复杂并且可能有很多性能问题。

答案 1 :(得分:0)

您需要调用tab控件的Invalidate()方法来强制重绘。像这样:

private int activeButton = -1;

private void tabControl1_MouseMove(object sender, MouseEventArgs e)
{
    int button;
    for (button = this.tabControl1.TabPages.Count-1; button >= 0; button--)
    {
        Rectangle r = tabControl1.GetTabRect(button);
        Rectangle closeButton = new Rectangle(r.Right - 15, r.Top + 4, 12, 12);
        if (closeButton.Contains(e.Location)) break;
    }
    if (button != activeButton) {
        activeButton = button;
        tabControl1.Invalidate();
    }
}

在DrawItem事件处理程序中使用activeButton变量来确定是否需要使用不同的颜色绘制它。

相关问题