Wednesday, August 27, 2008

C# Question

C# Question

I'm doing something so simple and obvious, that I can't find a web page that explains it anywhere. In C#, you can draw directly on the Form that comes up when the program starts. But the form includes any menu bar or other controls that you have in the window, and so if you starting drawing at 0,0, it disappears under the menu bar. It looks to me like the obvious way to do this (and the one suggested by how Java does it), is to create a Panel within the Form. What amazes me is that I can't seem to find an example anywhere that does this.

I cannibalized some code that I found out there to this:

public Form1()
{
InitializeComponent();
CreateMyPanel();
}

public void CreateMyPanel()
{
Panel panel1 = new Panel();
// Initialize the Panel control.
panel1.Location = new Point(56, 72);
panel1.Size = new Size(264, 152);
// Set the Borderstyle for the Panel to three-dimensional.
panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;

// Add the Panel control to the form.
this.Controls.Add(panel1);
}
This creates a Panel on the Form just fine. But the problem is that I want Panel events (such as something that invalidates the Panel) to invoke the OnPaint method to draw something in the Panel. But how do I do this? I know that there is some magic incantation that lets you register an event handler for a Panel so that all events get handed off to be executed, but I have not been able to find it. Help!

UPDATE: I received several useful responses from readers--one of them at Microsoft. The upside of an IDE like Visual Studio is that it does so much for you. And that's also the downside. It does so much for you that it is easy to lose track of what it has done. In case someone searches the web trying to find the same answer finds this:

1. Add the Panel to the Form using the [Design] tab and the Toolbox.

2. Right click on the Panel and select Properties (if you don't already have it up).

3. Click the lightning bolt icon in the Properties panel.

4. Double click the Paint property. Visual Studio creates the event handler, and adds the following line to Form1.Designer.cs:

this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);

Everything now works as I expected.

No comments:

Post a Comment