我正在使用此答案中的代码,并且运行良好!
但是,现在我需要添加一个悬停图像,因为没有悬停图像感觉很沉闷。
我已经画了图像,我只需要在悬停时更改图像,并在停止悬停时将其更改回来。
有一些建议Invalidate()
,但我不太明白如何使用它。
我尝试将以下代码放入MouseMove
事件中TabControl
,
for (var i = 0; i < this.tabControl1.TabPages.Count; i++)
{
var tabRect = this.tabControl1.GetTabRect(i);
tabRect.Inflate(-2, -2);
var imageRect = new Rectangle(tabRect.Right - CloseImage.Width,
tabRect.Top + (tabRect.Height - CloseImage.Height) / 2,
CloseImage.Width,
CloseImage.Height);
if (imageRect.Contains(e.Location))
{
isHover = true;
isNormal = false;
Invalidate(tabRect);
}
else
{
isNormal = true;
isHover = false;
Invalidate(tabRect);
}
}
但这似乎也不起作用。
变量isNormal
和isHover
已经在早期代码中创建,在DrawItem
事件内部,我有:
try
{
if (isHover == false && isNormal == true)
{
CloseImage = Properties.Resources.normalImage;
var tabRect = this.tabControl1.GetTabRect(e.Index);
tabRect.Inflate(-2, -2);
var imageRect = new Rectangle(tabRect.Right - CloseImage.Width,
tabRect.Top + (tabRect.Height - CloseImage.Height) / 2,
CloseImage.Width,
CloseImage.Height);
var sf = new StringFormat(StringFormat.GenericDefault);
if (this.tabControl1.RightToLeft == System.Windows.Forms.RightToLeft.Yes &&
this.tabControl1.RightToLeftLayout == true)
{
tabRect = GetRTLCoordinates(this.tabControl1.ClientRectangle, tabRect);
imageRect = GetRTLCoordinates(this.tabControl1.ClientRectangle, imageRect);
sf.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
}
e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text,
this.Font, Brushes.Black, tabRect, sf);
e.Graphics.DrawImage(CloseImage, imageRect.Location);
}
else if (isHover == true && isNormal == false)
{
CloseImage = Properties.Resources.hoverImage;
var tabRect = this.tabControl1.GetTabRect(tabControl1.SelectedIndex);
tabRect.Inflate(-2, -2);
var imageRect = new Rectangle(tabRect.Right - CloseImage.Width,
tabRect.Top + (tabRect.Height - CloseImage.Height) / 2,
CloseImage.Width,
CloseImage.Height);
var sf = new StringFormat(StringFormat.GenericDefault);
if (this.tabControl1.RightToLeft == System.Windows.Forms.RightToLeft.Yes &&
this.tabControl1.RightToLeftLayout == true)
{
tabRect = GetRTLCoordinates(this.tabControl1.ClientRectangle, tabRect);
imageRect = GetRTLCoordinates(this.tabControl1.ClientRectangle, imageRect);
sf.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
}
e.Graphics.DrawString(this.tabControl1.TabPages[tabControl1.SelectedIndex].Text,
this.Font, Brushes.Black, tabRect, sf);
e.Graphics.DrawImage(CloseImage, imageRect.Location);
isHover = false;
isNormal = true;
}
}
catch (Exception) { }
但它仍然无法正常工作。
如果我的问题不清楚,我深表歉意:)