1

我目前正在用 C# 制作一个应用程序,它使用LinkLabels. 我有一个函数可以为某个数组中的每个元素添加一个新链接。但是,该数组恰好有超过 32 个链接,当这种情况发生时,我会收到一个 OverflowException:

System.OverflowException:溢出错误。在 System.Drawing.StringFormat.SetMeasurableCharacterRanges(CharacterRange[] 范围) 在 System.Windows.Forms.LinkLabel.CreateStringFormat() 在 System.Windows.Forms.LinkLabel.EnsureRun(Graphics g) 在 System.Windows.Forms.LinkLabel.OnPaint (PaintEventArgs e) 在 System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer) 在 System.Windows.Forms.Control.WmPaint(Message& m) 在 System.Windows.Forms.Control.WndProc(Message& m) 在System.Windows.Forms.Label.WndProc(Message& m) 在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

有没有办法覆盖该SetMeasurableCharacterRanges功能。这样当字符范围超过 32 个时它不会抛出该错误?这是我的代码示例:

int LengthCounter = 0;
llbl.Links.Clear();
string[] props = AList.ToArray();

llbl.Text = string.Join(", ", props);
foreach (var Prop in props)
{
    llbl.Links.Add(LengthCounter, Prop.Length, string.Format("{0}{1}", prefix, Sanitize(Prop)));
    LengthCounter += Prop.Length + 2;
}
4

1 回答 1

2

SetMeasurableCharacterRanges是这样实现的:

/// <summary>Specifies an array of <see cref="T:System.Drawing.CharacterRange" /> structures that represent the ranges of characters measured by a call to the <see cref="M:System.Drawing.Graphics.MeasureCharacterRanges(System.String,System.Drawing.Font,System.Drawing.RectangleF,System.Drawing.StringFormat)" /> method.</summary>
/// <param name="ranges">An array of <see cref="T:System.Drawing.CharacterRange" /> structures that specifies the ranges of characters measured by a call to the <see cref="M:System.Drawing.Graphics.MeasureCharacterRanges(System.String,System.Drawing.Font,System.Drawing.RectangleF,System.Drawing.StringFormat)" /> method.</param>
/// <exception cref="T:System.OverflowException">More than 32 character ranges are set.</exception>
public void SetMeasurableCharacterRanges( CharacterRange[] ranges )
{
    int num = SafeNativeMethods.Gdip.GdipSetStringFormatMeasurableCharacterRanges( new HandleRef( this, this.nativeFormat ), ranges.Length, ranges );
    if( num != 0 )
        throw SafeNativeMethods.Gdip.StatusException( num );
}

StringFormat是密封的,方法SetMeasurableCharacterRanges不是虚拟的,所以你不能覆盖它。在内部,它对gdiplus.dll.

您可以尝试从继承自定义 LinkLabelLinkLabel并覆盖OnPaint()-method 并自己完成绘图。CreateStringFormat()(如果方法不是内部的,事情会更容易。)

或者您只是在 a上使用多个 LinkLabelsFlowLayoutPanel ,每个标签只有一个链接:

for( int i = 0; i < AList.Count; i++ )
{
    string prop = AList[i];
    LinkLabel llbl = new LinkLabel()
    {
        AutoSize = true,
        Margin = new Padding( 0 ),
        Name = "llbl" + i,
        Text = prop + ", "
    };
    llbl.Links.Add( 0, prop.Length, string.Format( "{0}{1}", prefix, Sanitize( prop ) ) );

    flowLayoutPanel1.Controls.Add( llbl );
}
于 2016-11-11T07:54:01.040 回答