Pergunta

Form what I have done so far in my program, it seems that the only way to draw anything on a winform is through System.Windows.Forms.PaintEventArgs. What if you don't have access to these arguments or this namespace and you only have access to the winform, how do you draw (say a shape like a rectangle) on a winform.

Thanks in advance.

Foi útil?

Solução

If you want to draw on the form (or any other control) outside of the Paint event, you have to get the Graphics object for that control. Then you can paint to your heart's content. Note, however, that the next time a paint message comes along, what you've drawn is likely to be erased.

To draw on the form:

using (Graphics g = this.CreateGraphics())
{
    // do all your drawing here
}

Outras dicas

PaintEventArgs is a class in the System.Windows.Forms namespace. If you're working with forms it means that you do have access to the namespace and the class, you may not however have access to the Form's code that you're attempting to draw on...

Even if you don't have access to the Form's source code, the Paint event is public and you can register a handler to it from code outside of the Form. (I'm guessing this is your issue.)

See this simple example class that has a reference to a Form, registers with the paint handler and then does some arbitrary drawing.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1 {
    class Painter {
        public Painter(Form form) {
            form.Paint += new PaintEventHandler(form_Paint);
        }

        void form_Paint(object sender, PaintEventArgs e) {
            e.Graphics.DrawLine(Pens.Black, 0, 0, 20, 20);
        }
    }
}

The important concept in this snippet is that if you have a reference to a form (or any Control-derived object) you can register with the paint event which gets called automatically whenever the control need to be repainted (and you can draw anything you want on that control.)

In the snippet I passed the Form in the constructor and registered with the paint event there but that was just for a quick example. Your code's structure will be different but... you will have a Form and there will be an initialization step where you register for the event and then create a method which does your painting.

You can draw other ways by creating and disposing your own Graphics object but this is not the preferable method. For one, you do not get notified when you need to redraw the window and would need to create other mechanisms for redrawing such as a timer (as a very simple and ugly example) and you would have to manage the Graphics object yourself.

You get access to them by subscribing to the Control.Paint event, and you perform all your drawing within the event handler you've subscribed. That will be provided with the relevant PaintEventArgs.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top