简体   繁体   English

System.Drawing.Pen - 标签放置在Form上时,行消失

[英]System.Drawing.Pen - lines disappear when Labels are placed on Form

I want to draw TextBoxes/Labels on my form in code and connect them with lines - based on data that I have stored in a datatable ("treedata"). 我想在代码中在我的表单上绘制TextBoxes / Labels并使用行连接它们 - 基于我存储在数据表(“treedata”)中的数据。 If I use the following code everything works fine: 如果我使用以下代码一切正常:

    For i = 0 To treedata.Rows.Count - 1

        Dim tb As New TextBox

        hor = treedata.Rows(i)(11)
        vern = ver + 120 * treedata.Rows(i)(4)

        tb.Text = "sometext"
        tb.Location = New Point(hor, vern)

        Form8.Controls.Add(tb)

        posofmodif = treedata.Rows(i)(10)
        vero = treedata.Rows(i)(6)

        Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Green)
        Dim formGraphics As System.Drawing.Graphics

        myPen.SetLineCap(LineCap.RoundAnchor, LineCap.ArrowAnchor, DashCap.Flat)
        formGraphics = Form8.CreateGraphics()
        formGraphics.DrawLine(myPen, Convert.ToSingle(posofmodif), Convert.ToSingle(vero), Convert.ToSingle(hor), Convert.ToSingle(vern))

        myPen.Dispose()
        formGraphics.Dispose()

    Next

However I would like to use labels instead of TextBoxes because it makes no sense to use heavier TextBoxes in this case. 但是我想使用标签而不是TextBoxes,因为在这种情况下使用较重的TextBox是没有意义的。 But when I simply replace 但是,当我简单地替换

Dim tb As New TextBox

by 通过

Dim tb As New Label

the labels do appear on the Form as expected but the lines connecting them appear only for a moment and then turn invisible. 标签确实按预期显示在表单上,​​但连接它们的线条只显示片刻然后变为不可见。

I first thought that the problem might be caused by labels being over or below the lines but even when I make sure that no line is crossing any label it happens. 我首先想到的问题可能是由于标签位于线条之上或之下,但即使我确保没有线条穿过任何标签,它也会发生。

Does anyone have an idea what I could do to avoid this? 有没有人知道我可以做些什么来避免这种情况?

This is your problem: Form8.CreateGraphics() . 这是你的问题: Form8.CreateGraphics() That method is volatile, as it creates a Graphics instance that does not survive the scope in which it's used. 该方法是易失性的,因为它创建的Graphics实例不能在其使用的范围内存活。

You need to be using the Paint event for whatever control on which you intend to draw. 您需要将Paint事件用于您要绘制的任何控件。 The form, the label...whatever that is. 形式,标签......不管是什么。 The Paint event provides a Graphics object for you to use, and it gets called whenever the drawing needs to be refreshed. Paint事件提供了一个Graphics对象供您使用,只要需要刷新绘图,就会调用它。

Because the event fires frequently, you need to be mindful of what you do there. 因为事件经常发生,你需要注意你在那里做的事情。 Heavy lifting in a Paint handler can slow an app down considerably. Paint处理程序中的繁重工作可以大大减慢应用程序的速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM