Reputation: 59
I'm new to c# so that is probably the majority of my problem of not understanding how the paint event work. I have a code that paints a series of rectangles. I want to have it display using GDI+ when the space bar is pressed. I have everything working properly if I don't use the key event to call the drawing class. My problem is that when I put the new paint event handler into my spacebar event handler, nothing happens. I have removed some of my code to make it easier to see for the sake if this question. Thanks in advance.
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Timers;
using System.Windows.Input;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
public class Drawgra : Form
{
public static void Main()
{
Application.Run(new Drawgra());
}
public Drawgra()
{
int screenheight = 950; int screenwidth = 1600;
this.Size = new Size(screenwidth, screenheight);
ConsoleKeyInfo key;
key = Console.ReadKey(true);
this.KeyPreview = true;
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
// this.Paint += new PaintEventHandler(Draw_outlines);
}
public void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
this.Paint += new PaintEventHandler(Draw_outlines);
}
}
public void Draw_outlines(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen box = new Pen(Color.Black, 20);
g.DrawRectangle(box, 100, 0, 200, 400);
}
}//close form
Upvotes: 1
Views: 626
Reputation: 888087
You need add the event handler just once, not once per keystrike, then call Invalidate()
on every keystroke to make it redraw and trigger the handler.
Upvotes: 1