Windows Forms C# TabControl ImageList Alignment?

瘦欲@ 提交于 2019-12-12 04:04:23

问题


Is it possible to align the image icon from on a TabControl's ImageList to the right of the text?

Right now, the image icon gets put on the left, and the text is to the right of that. I would prefer the text to be on the left, and the icon to the right of that. Is this possible?


回答1:


You can not do that unless you Draw the TabPage yourself. To do that you need to set the DrawMode property of the TabControl to OwnerDrawFixed and then handle the DrawItem Event.
This is a very simple example to do that, you can add some code to change the background color of the selected tab if you wish, to know which tab is selected just check the e.State value:

private void tabControl1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
    // values
    TabControl tabCtrl = (TabControl)sender;
    Brush fontBrush = Brushes.Black;
    string title = tabCtrl.TabPages[e.Index].Text;
    StringFormat sf = new StringFormat();
    sf.Alignment = StringAlignment.Near;
    sf.LineAlignment = StringAlignment.Center;
    int indent = 3;
    Rectangle rect = new Rectangle(e.Bounds.X, e.Bounds.Y + indent, e.Bounds.Width, e.Bounds.Height - indent);

    // draw title
    e.Graphics.DrawString(title, tabCtrl.Font, fontBrush, rect, sf);

    // draw image if available
    if (tabCtrl.TabPages[e.Index].ImageIndex >= 0)
    {
        Image img = tabCtrl.ImageList.Images[tabCtrl.TabPages[e.Index].ImageIndex];
        float _x = (rect.X + rect.Width) - img.Width - indent;
        float _y = ((rect.Height - img.Height) / 2.0f) + rect.Y;
        e.Graphics.DrawImage(img, _x, _y);
    }
}


来源:https://stackoverflow.com/questions/10261436/windows-forms-c-sharp-tabcontrol-imagelist-alignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!