I am making a basic sketch program for university. So far its going ok and drawing lines with up, down, left, right.
But I want to set the letter C to clear the program.
I get the error "The name 'g' does not exist in the current context".
Is it to do with the protected override bool?
My code is below.
Thanks in advance.
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespaceEtchaSketch
{
publicpartialclassForm1 : Form
{
int x = 50, y = 50; // starting position
Bitmap bm;
int x1 = 50, y1 = 50;
publicForm1()
{
InitializeComponent();
}
privatevoidForm1_Load(object sender, EventArgs e)
{
bm = new Bitmap(this.Width, this.Height); // create a form-size bitmap
Graphics g = Graphics.FromImage(bm); // get a graphic object for the bitmap
g.FillEllipse(Brushes.Blue, x, y, 20, 20); // put a circle in the bitmapthis.BackgroundImage = bm; // use the bitmap as the form background
}
privatevoidForm1_Paint(object sender, PaintEventArgs e)
{
Graphics g = Graphics.FromImage(bm); // get a graphic object for the bitmap
g.FillEllipse(Brushes.Blue, x1, y1, 20, 20);
}
protectedoverrideboolProcessCmdKey(ref Message msg, Keys keyData)
{
string input;
input = keyData.ToString();
if (input == "Down")
{
y1 = y1 + 10;
Refresh();
returntrue;
}
if (input == "Up")
{
y1 = y1 - 10;
Refresh();
returntrue;
}
if (input == "Left")
{
x1 = x1 - 10;
Refresh();
returntrue;
}
if (input == "Right")
{
x1 = x1 + 10;
Refresh();
returntrue;
}
if (input == "C")
{
g.Clear(BackColor);
Refresh();
returntrue;
}
returnfalse; // return true if key processed, otherwise false
}
}
}
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Graphics g = Graphics.FromImage(bm); declared in both the Form1_Load and Form1_Paint event. ProcessCmdKey method cannot access the g variable declared in those events.. Can you make Graphics g = Graphics.FromImage(bm); public? or include Graphics g = Graphics.FromImage(bm); in ProcessCmdKey.
Bryian TanRank #396 · 6.3K reputationPosted May 10, 2010, 8:31 PM EDT
Graphics g = Graphics.FromImage(bm); declared in both the Form1_Load and Form1_Paint event. ProcessCmdKey method cannot access the g variable declared in those events.. Can you make Graphics g = Graphics.FromImage(bm); public? or include Graphics g = Graphics.FromImage(bm); in ProcessCmdKey.