Okay, so I'm creating a class in C#. It works fine, so I'm adding more methods. This is meant to port some BASIC commands as methods into C#. I want to create a method that'll automatically do graphics without having to manually set up pens, points, graphics, etc. Just type in a command. The problem is that...well...it won't work. When I compile, it runs, but it throws an exception when I call the method (Object reference not set to an instance of an object
). I know what the exception is telling me, but I can't figure out how to fix it. Here's my current code:
Graphics g;
public void gpset(int x1, int y1, string colour1)
{
Pen myPen = new Pen(Color.FromName(colour1));
g.DrawLine(myPen, x1, y1, x1 + 1, y1 + 1);
myPen = new Pen(Color.White);
g.DrawLine(myPen, x1 + 1, y1, x1 + 1, y1 + 1);
myPen.Dispose();
g.Dispose();
}
public void gline(int x1, int y1, int x2, int y2, string colour1)
{
Pen myPen = new Pen(Color.FromName(colour1));
g.DrawLine(myPen, x1, y1, x2, y2);
myPen.Dispose();
g.Dispose();
}
public void gbox(int x1, int y1, int x2, int y2, string colour1)
{
Pen myPen = new Pen(Color.FromName(colour1));
g.DrawRectangle(myPen, x1, y1, x2, y2);
myPen.Dispose();
g.Dispose();
}
Since this didn't work, I tried to do this instead of Graphics g;
PaintEventArgs e;
Graphics g = e.Graphics();
Now it simply won't compile. It says A field initializer cannot reference the non-static field, method, or property 'SmileB.SmileB.e'
.
I've also tried doing:
PaintEventArgs e;
//Later in the code:
method stuff here()
{
other stuff here;
e.Graphics.<command>;
}
But this doesn't seem to work either. Help? Is this even possible to do? Also, I've run these methods directly inside of a forms application, and they work, so the methods themselves seem not to be the problem.
EDIT: Also, is there a better way to do the gpset
method? It should just create one pixel of colour.
EDIT EDIT: Here's how I'm declaring the class:
using SmileB;
namespace Drawing_Test
{
public partial class Form1 : Form
{
SmileB.SmileB ptc = new SmileB.SmileB();
//Down here is where I use the code
}
}