SystemPens cause Exception error

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
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
 
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.
 
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
 
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();
 
Back
Top