Drawing a simple triangle in C#? Help!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Paul Johnson
    New Member
    • Oct 2010
    • 97

    Drawing a simple triangle in C#? Help!

    Hi,

    I have a winform and am trying to just draw a triangle on it. I don't want it inside of an event.

    Currently, the code I have is just this

    Code:
        public partial class Triangles : Form
        {
            public Triangles()
            {
                InitializeComponent();
                drawTriangle();
            }
    
            private void drawTriangle()
            {
                Graphics surface;
                surface = this.CreateGraphics();
                SolidBrush brush = new SolidBrush(Color.Blue);
                Point[] points = {new Point(10, 10), new Point(100, 10), new Point(50, 100) };
                surface.FillPolygon(brush, points);
            }
        }
    Nothing draws. I've added an invalidate to the end incase that was the hitch, but still, nada.

    Could any kind soul please point the way on this? Line and filled polygons are something I've never needed to play with - until now...

    Thanks

    Paul
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    You say you don't want your draw inside an event, but you kind of have to if you want it to persist on your form. WinForms uses events to control when an object gets drawn, it uses this so it knows to repaint after a window moves, something obscures it, or it becomes visible.

    If you don't want this, you could probably get away with what you're doing if you draw and your window doesn't get repainted, but you don't have a lot of control over that. You can manually trigger a repaint, and you can stop them from occurring at all, but other than that windows will paint when it feels it needs to.

    With the code you have here, you're doing your paint in the constructor before your form ever draws. So your triangle will disappear as soon as your form shows. If you are dead set against using the proper painting methods, try putting your triangle draw in the Load event on your form, this might happen after the last refresh but I'm not sure. Another alternative is to have it paint in response to a button click.

    The best way is to just override the Paint event and do all your drawing in there. If you need that paint to occur repeatedly (ie, for animation), just put a timer on your form and call the form's Invalidate method to trigger a redraw.

    If you have any questions or need help getting the code going, please feel free to ask more questions :)

    Comment

    • Paul Johnson
      New Member
      • Oct 2010
      • 97

      #3
      Hi Gary,

      Thanks. I've done as you've suggested and life is good :)

      Paul

      Comment

      Working...