SystemPens cause Exception error

T

Tony Johansson

Hi!

This example is from e-learning. It cause exception error at line 3 when
trying to change the DashStyle.
The exception is translated to english "ArgumentException was unhandled
It's not possible to make changes in the Pen because the priviligier are not
valid"

private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = this.CreateGraphics();
Pen pen = SystemPens.ActiveBorder;
pen.DashStyle = DashStyle.Solid;
pen.Width = 2;
g.DrawLine(pen, 10, 10, 200, 10);
pen.Dispose();
}

So why is it not possible to change a pen object that has been returned from
a SystemPen ?

//Tony
 
A

Alberto Poblacion

Tony Johansson said:
[...]
So why is it not possible to change a pen object that has been returned
from a SystemPen ?

The SystemPen returns a static object, so if you were to change it, you
would also chage that system pen anywhere else that it might be in use.
If you want to make changes to a pen, you should get a "new Pen(...)"
rather than attempting to use one of the static pens.
 
C

Chris Dunaway

Hi!

This example is from e-learning. It cause exception error at line 3 when
trying to change the DashStyle.
The exception is translated to english "ArgumentException was unhandled
It's not possible to make changes in the Pen because the priviligier are not
valid"

private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = this.CreateGraphics();
Pen pen = SystemPens.ActiveBorder;
pen.DashStyle = DashStyle.Solid;
pen.Width = 2;
g.DrawLine(pen, 10, 10, 200, 10);
pen.Dispose();
}

So why is it not possible to change a pen object that has been returned from
a SystemPen ?

//Tony

You should not dispose any of the system pens. That could cause
problems. Also, don't call CreateGraphics, instead, use the graphics
instance provided to you in the PaintEventArgs: e.Graphics.

See this link:

http://www.bobpowell.net/creategraphics.htm

Chris
 
J

Jeff Johnson

This example is from e-learning. It cause exception error at line 3 when
trying to change the DashStyle.
The exception is translated to english "ArgumentException was unhandled
It's not possible to make changes in the Pen because the priviligier are
not valid"

private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = this.CreateGraphics();
Pen pen = SystemPens.ActiveBorder;
pen.DashStyle = DashStyle.Solid;
pen.Width = 2;
g.DrawLine(pen, 10, 10, 200, 10);
pen.Dispose();
}

So why is it not possible to change a pen object that has been returned
from a SystemPen ?

Because you have THE Pen which is part of the SystemPens class, not A Pen
which is a duplicate of that Pen. What you should really do is this:

Pen pen = (Pen)SystemPens.ActiveBorder.Clone();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top