Home > Software engineering >  C# How to call method with PaintEventArgs from KeyDown method
C# How to call method with PaintEventArgs from KeyDown method

Time:11-03

I'm learning Form Applications and very new to whole way of how this works. I want to paint something on the screen (line) on user key press but I cant figure out how to parse the PaintEventArgs to the method. I've read different post but I do not understand what I'm actually supposed to do. Most of the say use PictureBox tried a few things but cant call the paint from KeyDown Method.

I have also added my KeyDown method inside the InitializeComponent.

this.KeyDown = new KeyEventHandler(this.Form1_KeyDown);

Thanks in advance.

Code:

private void Form1_KeyDown(object sender, KeyEventArgs ke)
{
    if (ke.KeyCode == Keys.Space)
    {
        Custom_Paint(sender, needPaintEventArgsHere);
    }
}

private void Custom_Paint(object sender, PaintEventArgs pe)
{
    Graphics g = pe.Graphics;
    Pen blackPen = new Pen(Color.Black, 1);

    pe.Graphics.DrawLine(blackPen, 200.0F, 400.0F, 500.0F, 700.0F);
}

CodePudding user response:

When you inherit from the Form class, you don't need to subscribe the events such as KeyDown, KeyUp or Paint. Instead, you should override the corresponding methods OnKeyDown, OnKeyUp, OnPaint. In your case, you should write your draw logic inside the overriden OnPaint method and draw directly on the Graphics object passed through PaintEventArgs.Graphics. After that, when you need a repaint, just call Control.Invalidate to trigger the OnPaint method.

Also, you might want to enable double-buffering for your Form as shown in the constructor.

public partial class Form1: Form
{
   public Form1()
   {
       SetStyle(ControlStyle.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true);
       InitializeComponent();
   }
   protected override void OnPaint(object sender, PaintEventArgs e)
   {
       Graphics g = e.Graphics;
       Pen blackPen = new Pen(Color.Black, 1);

       g.Graphics.DrawLine(blackPen, 200.0F, 400.0F, 500.0F, 700.0F);
   }
   protected override void OnKeyUp(KeyEventArgs e)
   {
       if (ke.KeyCode == Keys.Space)
           Invalidate();
   }

}

  • Related