views:

210

answers:

1

I'm coming from a Java background and trying to port a simple version of Conway's Game of Life that I wrote to C# in order to learn the language.

In Java, I drew my output by inheriting from JComponent and overriding paint(). My new canvas class then had an instance of the simulation's backend which it could read/manipulate. I was then able to get the WYSIWYG GUI editor (Matisse, from NetBeans) to allow me to visually place the canvas.

In C#, I've gathered that I need to override OnPaint() to draw things, which (as far as I know) requires me to inherit from something (I chose Panel). I can't figure out how to get the Windows forms editor to let me place my custom class. I'm also uncertain about where in the generated code I need to place my class.

How can I do this, and is putting all my drawing code into a subclass really how I should be going about this? The lack of easy answers on Google suggests I'm missing something important here. If anyone wants to suggest a method for doing this in WPF as well, I'm curious to hear it.

Thanks

+2  A: 

In Windows Forms, you can simply draw on any control by calling its CreateGraphics method. If you have a panel, for example, you can draw like this:

using (var g = panel1.CreateGraphics()) {
    g.DrawString("Hello World", 0, 0);
}

Controls also have a Paint event. Add an event handler by double-clicking the event in the properties window, and you can draw like this:

private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    e.Graphics.DrawString("Hello World", 0, 0);
}

If you want to derive from a control, you can either just do it in code, or create a new user control and change the base class in the code and in the .Designer.cs file (though UserControl or just Control will be fine). If you already have a form in the designer, it's already derived from Form, and you can just override OnPaint.

My advice is: You typically won't need to create a new class if you just want to draw something. Just use the Paint event. If you need to immediately redraw, call Refresh to make the control redraw itself. This should get you going. Note that there is also a protected DoubleBuffered property, which can help you avoid flickering (set it for the form or in your derived control).

I'm not sure what you would do in WPF. I never needed to actually draw something manually in WPF, since the layout and rendering engine is very powerful, and you can just get away with data templates, control templates etc. The point in WPF is that you typically don't draw anything, the engine draws for you.

OregonGhost
Thank you, this is exactly what I needed to know!
Joel
In that case, you may want to accept my answer by clicking the check mark to the left :)
OregonGhost
Haha, thanks. I'm new here :P
Joel